2015-09-27 156 views
0

我正在構建一個自動完成下拉框,並且我有一個函數式SQL調用,它會查找我正在搜索的內容,但是當我嘗試將其集成時爲適當的PDO聲明我不能動搖此錯誤消息:PHP/PDO SQLSTATE [42000]:語法錯誤或訪問衝突:1064夢魘

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 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 city LIKE CONCAT('van', '%') ORDER BY display_value' at line 1' in /home/asdf/index-ajax.php:61 
Stack trace: 
#0 /home/asdf/index-ajax.php(61): PDOStatement->execute(Array) 
#1 {main} 
    thrown in /home/asdf/index-ajax.php on line 61 

這裏是我的代碼:

$qry = $CFG["DBH"]->prepare("SELECT DISTINCT CONCAT(city, ', ', prov_stat, ', ', country) AS display_value FROM `contact` AND city LIKE CONCAT('%', :contactCity, '%') ORDER BY display_value;"); 
$qry->execute(array(':contactCity' => "van")); 

我試過發現,談論這個消息的引用,它的原因和如何這樣做,但它似乎很常見,我已經能夠閱讀但沒有包含一個馬gic子彈。任何人都可以在我的代碼中看到問題嗎?

+1

你錯過了'WHERE'條款。看看'AND'在寒冷中獨自一人坐在那裏。記住SQL傾向於像一個句子一樣閱讀。大聲朗讀您的查詢,看看它是否有意義! – Parfait

+0

「FROM'contact' AND city不是有效的SQL。」真的是「噩夢」......誇大了多少? –

回答

2

這已經有一段時間,因爲我寫的SQL,但事情似乎離你列的列表:

$qry = $CFG["DBH"]->prepare("SELECT DISTINCT CONCAT(city, ', ', prov_stat, ', ', country) AS display_value FROM `contact` AND city LIKE CONCAT('%', :contactCity, '%') ORDER BY display_value;"); 
$qry->execute(array(':contactCity' => "van")); 

我不認爲你可以加入兩列AND在一起,特別是沒有您已選擇表格。另外,就我所知,您無法直接在SELECT中過濾您的查詢(WHERE)。

像這樣的東西可能會奏效:

$qry = $CFG["DBH"]->prepare(
    "SELECT DISTINCT 
     CONCAT(city, ', ', prov_stat, ', ', country) AS display_value, 
     city 
    FROM `contact` 
    WHERE city LIKE CONCAT('%', :contactCity, '%') 
    ORDER BY display_value;" 
); 

$qry->execute(array(':contactCity' => "van")); 
+0

@rockerfest你是對的,我在我的陳述中錯過了一些項目,我有一個問題,提前2天開始,並在我試圖解決它,我修剪出超過我應該有..這是實際完整的SQL語句:'SELECT DISTINCT CONCAT(city,',',prov_stat,',',country)AS display_value FROM'contact' WHERE city IS NOT NULL AND TRIM(city)!=''AND prov_stat IS NOT NULL AND TRIM (prov_stat)!=''AND country is NOT NULL AND TRIM(country)!=''AND'city' LIKE CONCAT('%',:contactCity,'%')ORDER BY display_value; – Vince

相關問題