我有這樣的代碼:MySQL錯誤1064執行SELECT查詢時
function search_keyword(){
$keyword = trim($_POST['keyword']);
$search_explode = explode(" ", $keyword);
$x = 0;
$sql = " (SELECT name, id_global_info AS id, body AS body, tag AS tag ,info_type_id AS info_type, \"global_info\" AS mytable FROM global_info WHERE ";
foreach($search_explode as $each){
$x++;
if($x == 1){
$sql .= " name LIKE '%$each%' ";}
else {
$sql .= " AND name LIKE '%$each%' ";
}
}
$sql .= ") UNION ALL ";
$sql .= " (SELECT name, id_person AS id, surname AS body, info AS tag , location AS info_type, \"person\" AS mytable FROM person WHERE ";
foreach($search_explode as $each){
$x++;
if($x == 1){
$sql .= " name LIKE '%$each%' ";}
else {
$sql .= " AND name LIKE '%$each%' ";
}
}
$sql .= ") UNION ALL ";
$sql .= "(SELECT name, id_event AS id, body AS body, caffe_id AS tag , date AS info_type, \"event\" AS mytable FROM event WHERE ";
foreach($search_explode as $each){
$x++;
if($x == 1){
$sql .= " name LIKE '%$each%' ";}
else {
$sql .= " AND name LIKE '%$each%' ";
}
}
$sql .= ") UNION ALL ";
$sql .= "(SELECT name, id_caffe AS id, description AS body, adress AS tag, location_id AS info_type, \"caffe\" AS mytable FROM caffe WHERE ";
foreach($search_explode as $each){
$x++;
if($x == 1){
$sql .= " name LIKE '%$each%' ";}
else {
$sql .= " AND name LIKE '%$each%' ";
}
}
$sql .= ") ";
echo $sql;
$q = $this->db->query($sql);
return $q = $q->num_rows() == 0 ? FALSE : $q->result();
}
當我搜索exapmle
"mali oglasi"
我獲得以下錯誤:
Error Number: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'AND name LIKE '%mali%' AND name LIKE '%oglas%') UNION ALL ( SELECT name, id_e' at line 1
這是MySQL正在生成查詢:
(SELECT name, id_global_info AS id, body AS body, tag AS tag ,info_type_id AS info_type, "global_info" AS mytable FROM global_info WHERE name LIKE '%mali%' AND name LIKE '%oglas%')
UNION ALL
(SELECT name, id_person AS id, surname AS body, info AS tag , location AS info_type, "person" AS mytable FROM person WHERE AND name LIKE '%mali%' AND name LIKE '%oglas%')
UNION ALL
(SELECT name, id_event AS id, body AS body, caffe_id AS tag , date AS info_type, "event" AS mytable FROM event WHERE AND name LIKE '%mali%' AND name LIKE '%oglas%')
UNION ALL
(SELECT name, id_caffe AS id, description AS body, adress AS tag, location_id AS info_type, "caffe" AS mytable FROM caffe WHERE AND name LIKE '%mali%' AND name LIKE '%oglas%')
什麼似乎是錯誤?
我已經改變了你建議的方式,但我仍然得到同樣的錯誤 – Sasha 2012-03-29 12:54:02
@Sasha對不起 - 我聽錯了。這裏真正的問題是,您需要將'$ x'的值重置爲每個foreach循環的零。 – 2012-03-29 12:57:01
這是問題所在。謝謝 :) – Sasha 2012-03-29 13:01:06