如何查询单词没有'(单引号)并显示结果'(单引号)?

时间:2018-02-28 08:08:53

标签: php mysql

我想从数据库中搜索单词,单词引用就像一个单词不能,如果我搜索单词如cant而没有单引号,则仍然无法显示。

    <?php
    // Attempt search query execution
    try{

        if(isset($_REQUEST['term'])){
            // create prepared statement
            $sql = "SELECT * FROM countries WHERE name LIKE :term";
            $stmt = $pdo->prepare($sql);
            $term = '%' . $_REQUEST['term'] . '%';
            // bind parameters to statement
            $stmt->bindParam(':term', $term);
            // execute the prepared statement
            $stmt->execute();
            //fetch the data if there is a name and else no matches found
            if($stmt->rowCount() > 0){
                while($row = $stmt->fetch()){
                    echo "<p>" . $row['name'] . "</p>";
                }
            } else{
                echo "<p>No matches found</p>";
            }
        }  
    } catch(PDOException $e){
        die("ERROR: Could not able to execute $sql. " . $e->getMessage());
    }
    // Close statement
    unset($stmt);
    // Close connection
    unset($pdo);
    ?>

1 个答案:

答案 0 :(得分:1)

您可以替换所有不需要的字符:

REPLACE(name, '#','')

在你的情况下:

SELECT * FROM countries WHERE REPLACE(name, '\'','') LIKE :term

如果你想要删除更多特殊字符,你需要这样做:

SELECT * FROM countries WHERE REPLACE(REPLACE(name, '\'',''), '*', '') LIKE :term