我不明白为什么以下查询不会返回任何内容。如果我更改了查询,那么它会返回结果。
我现在在做什么(没有输出)
$msg = array();
$getSearch = "SELECT contact_details . * , company.company_name, users.nickname FROM contact_details LEFT JOIN users ON users.user_id = contact_details.user_id LEFT JOIN company ON company.cid = contact_details.cid WHERE";
if(!empty($ad_company)){
$getSearch .= "company.company_name LIKE '$ad_company%' ";
}
$getSearch = mysql_query($getSearch);
while($searchResult = mysql_fetch_array($getSearch)){
$msg[] = $company = $searchResult['company_name'] . "<br/>";
}
echo json_encode($msg);
更改代码(工作)
$msg = array();
$getSearch = "SELECT contact_details . * , company.company_name, users.nickname FROM contact_details LEFT JOIN users ON users.user_id = contact_details.user_id LEFT JOIN company ON company.cid = contact_details.cid WHERE company.company_name LIKE '$ad_company%'";
//$msg[] = empty($ad_company) ? "empty company" : "not empty company"; //for checking and field has value
/*if(!empty($ad_company)){
$getSearch .= "company.company_name LIKE '$ad_company%' ";
}*/
$getSearch = mysql_query($getSearch);
while($searchResult = mysql_fetch_array($getSearch)){
$msg[] = $company = $searchResult['company_name'] . "<br/>";
}
echo json_encode($msg);
答案 0 :(得分:2)
也许是因为你在WHERE和公司之间没有空间?
答案 1 :(得分:1)
试试这个
作为Mitja的回答,你错过了WHERE和公司之间的空间
$getSearch = "SELECT contact_details . * , company.company_name, users.nickname
FROM contact_details
LEFT JOIN users ON users.user_id = contact_details.user_id
LEFT JOIN company ON company.cid = contact_details.cid ";
if(!empty($ad_company)){
$getSearch .= " WHERE company.company_name LIKE '$ad_company%' ";
}
<强> EDITED 强>
$getSearch = "SELECT contact_details . * , company.company_name, users.nickname
FROM contact_details
LEFT JOIN users ON users.user_id = contact_details.user_id
LEFT JOIN company ON company.cid = contact_details.cid
WHERE 1=1 ";
if(!empty($ad_company)){
$getSearch .= " AND company.company_name LIKE '$ad_company%' ";
}
答案 2 :(得分:0)
我已从您的$ getSearch查询中删除了WHERE,并将其添加到我们要附加的
中 $getSearch = "SELECT contact_details . * , company.company_name, users.nickname FROM contact_details LEFT JOIN users ON users.user_id = contact_details.user_id LEFT JOIN company ON company.cid = contact_details.cid";
if(!empty($ad_company)){
$getSearch .= " WHERE company.company_name LIKE '$ad_company%' ";
}
将来如果你遇到这样的问题总是尝试在用db查询之前只打印sql查询..这样你就会看到你的查询是否正确