2012-07-17 107 views
0

嘿傢伙我正在這裏這個小功能PDO返回MySQL錯誤與bindParam

function getBeaches() { 

$request=Slim::getInstance()->request(); 

$args=filter_var_array(func_get_args(),FILTER_SANITIZE_STRING); 
$sql="SELECT * FROM beaches WHERE state=:state AND city=:city"; 

    // var_export($args); die(); 
    // array (0 => 'wa', 1 => 'seattle',) 

try { 
    $db   = getConnection(); 
    $stmt  = $db->prepare($sql); 


     $stmt->bindValue('state', $args[0], PDO::PARAM_STR); //should bind wa 
     $stmt->bindValue('city', $args[1], PDO::PARAM_STR); //should bind seattle 
     $stmt->execute(); 

    $stmt  = $db->query($sql); 
    $beaches = $stmt->fetchObject(); 
    $db   = null; 

    echo '{"map": ' . stripslashes(json_encode($beaches)) . '}'; 
} catch(PDOException $e) { 
    echo '{"error":{"text":'. $e->getMessage() .'}}'; 
} 

    /* {"error":{"text":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 ':state AND city=:city' at line 1}} 
    */ 

} 

而且我得到我在底部評論的錯誤,試圖像這樣

mysql$ SELECT * FROM beaches WHERE state='wa' AND city='seattle';

運行此

可能是這枚戒指的一些鐘聲?

回答

3

你之前,你的名字PARAM需要的分號: (不是100%正確,請參閱編輯)

$stmt->bindValue(':state', $args[0], PDO::PARAM_STR); //should bind wa 
$stmt->bindValue(':city', $args[1], PDO::PARAM_STR); //should bind seattle 

從PHP文檔上PDOStatement::bindValue()

參數標識。對於使用命名佔位符的預準備語句,這將是形式的參數名稱:名稱。對於使用問號佔位符的準備好的語句,這將是參數的1索引位置。

編輯 作爲@jeroen指出,則會覆蓋$stmt變量,你從它那裏得到的數據之前的問題(同一個在你的引擎收錄)。在你的代碼的問題是圍繞17日線:

$stmt->execute(); 
$beaches = $stmt->fetchObject(); 
+0

這不是真的,bindParam和bindValue並且沒有冒號運行。 – ehime 2012-07-17 00:47:22

+1

注意它們冒號':'不是分號';'; – Martin 2012-07-17 00:49:10

+1

@ehime這是非常真實的(對於你使用分號的情況)。看看你的錯誤證明。 MySQL正在接收':state AND city =:city',因爲這些值沒有被替換。當然你可以使用另一個前綴字符(比如'@'或根本就沒有),但這不是手冊推薦的。無論你做什麼,你傳入'bindValue()'的參數標識符(docs中的'$ parameter')必須與你的字符串中的參數標識符完全匹配。 – 2012-07-17 00:49:47

0

不知道是否有幫助,但我總是用bindParambindValue

$stmt->execute(); // $stmt now has query results (from the query with parameters bounded) 

$stmt  = $db->query($sql); // You redo the query. Now $stmt has no query results and no parameters are bound 
$beaches = $stmt->fetchObject(); // Statement assumes you want to execute query and does so but not parameters are bound 

您可以通過上面的行更改爲解決這個問題。如果你選擇這樣做,修改粘合劑這樣:

$stmt->bindParam(':state', $args[0], PDO::PARAM_STR); 
$stmt->bindParam(':city', $args[1], PDO::PARAM_STR); 

其他,你做的一切看起來好像沒什麼問題。

+0

我使用'bindParam'首先,但產生相同的錯誤,我是想知道如果我沒有通過參考,所以切換到價值,只是爲了檢查。雖然相同的錯誤=( – ehime 2012-07-17 00:55:40