我正在研究为什么看似正确的 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/