php - 使用 MySQL 查询返回正确数据时遇到问题

标签 php mysql

我正在研究为什么看似正确的 mysql 查询没有返回正确的结果。我得到了几个文件要查看,我相信这(下面的代码)是罪魁祸首。不幸的是,我没有所有的文件(为 friend 做这件事)所以我很难做任何 var_dumps 或测试。相反,我创建了自己的模拟搜索脚本,它返回正确的结果——尽管查询是相同的。

原创:

function build_generic_where_clause ($the_query_string) {
    $where_clauses = Array();
    $the_query_string = $this->db->quote($the_query_string);
    array_push($where_clauses, "accounts.name like '%$the_query_string%'");
    if (is_numeric($the_query_string)) {
        array_push($where_clauses, "accounts.phone_alternate like '%$the_query_string%'");
        array_push($where_clauses, "accounts.phone_fax like '%$the_query_string%'");
        array_push($where_clauses, "accounts.phone_office like '%$the_query_string%'");
    }

    $the_where = "";
    foreach($where_clauses as $clause)
    {
        if(!empty($the_where)) $the_where .= " or ";
        $the_where .= $clause;
    }

    return $the_where;
}

但是这个失败了,因为我要说两个项目,例如:

Newstate Inc.
Welders of New York

并且上面的查询只返回 Newstate。但是,如果我在搜索框中键入 %new,则会返回这两个项目。我需要得到它,只要输入"new"就会返回它们。

我的测试模拟查询:

public static function getAccount($the_query_string){
    $con = drake::connectDB();

    $query = "select * from accounts where name like '%$the_query_string%'";

    $result = $con->query($query);
    while($row = $result->fetch_array()){
        echo($row['name']).'<br />';    
    }
}

并且当搜索“new”时,那个人成功地返回了这两个项目。我最好的猜测是 $this->db->quote($the_query_string);正在向搜索字符串添加一些内容,以某种方式改变它,因此它不会准确返回查询的内容。任何帮助将非常感激。

最佳答案

我觉得你可以用

$the_query_string = mysql_real_escape_string($the_query_string)

消除任何需要转义的意外或特殊字符。希望这对您有所帮助。 请在评论中让我知道状态。

关于php - 使用 MySQL 查询返回正确数据时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16175543/

相关文章:

php - 计算数据库中特定字段的字符数

javascript - 如何用 php 数组值替换 jquery 变量值

mysql - 使用mysqlbinlog命令找不到文件

php - mysql插入(使用到期日期)

mysql - 有没有办法测试通配符选择中所有列的空值?

sql - 减去列值后在sql中排序

php - 如何使用php防止同一记录在mysql中插入两次

php - 如何在 php 中执行搜索?

php - 检查二维数组的 PHP 数组键

php - 如何从 $_POST 获取数据数组