2012-06-15 78 views
4

我想用數組形式的參數使用簡單的MySQL插入查詢。它一直告訴我參數的數量是錯誤的。我曾嘗試以下,所有生產的同樣的錯誤:PDO錯誤:「無效的參數號:參數未定義」

$stmt3 = $link->prepare('INSERT INTO messages VALUES(null, :room, :name, :message, :time, :color)'); 
$stmt3->execute(array(':room' => $Clean['room'],':name' => $Clean['name'],':message' => $Clean['message'],':time' => $time,':color:' => $Clean['color'])); 

$stmt3 = $link->prepare('INSERT INTO messages VALUES(:null, :room, :name, :message, :time, :color)'); 
$stmt3->execute(array(':null' => null, ':room' => $Clean['room'],':name' => $Clean['name'],':message' => $Clean['message'],':time' => $time,':color:' => $Clean['color'])); 

以及聲明的列特地避開了空的insert:

$stmt3 = $link->prepare('INSERT INTO messages (room, name, message, time, color) VALUES(:room, :name, :message, :time, :color)'); 
$stmt3->execute(array(':room' => $Clean['room'],':name' => $Clean['name'],':message' => $Clean['message'],':time' => $time,':color:' => $Clean['color'])); 

這是我的第一次使用PDO(我通常使用mysqli,但我目前的共享主機沒有mysqlnd插件,使我無法使用prepare(),所以從這個角度來看任何洞察力都是值得讚賞的。

回答

18

這個問題 - 你會踢自己 - 與:color

調用​​時爲該標記傳遞的值的數組鍵值爲:color:。刪除尾隨:(我猜這只是一個錯字)。

$stmt3->execute(array(
    ':room' => $Clean['room'], 
    ':name' => $Clean['name'], 
    ':message' => $Clean['message'], 
    ':time' => $time, 
    ':color' => $Clean['color'], 
    )); 
+1

哦,我的上帝。我現在恨自己。我不敢相信我盯着這裏一個半小時,並沒有看到它...... – Morgan

+7

花了我幾分鐘。有時你只需要新鮮的眼睛,這就是我們在這裏;-) – DaveRandom

+1

hehehe +1爲新鮮的眼睛!尼斯趕上戴夫 – Adi

-1

我可能是錯在這裏,但據我所知,你需要這樣做:

$stmt3->bindParam(':room', $Clean['room']); 
$stmt3->bindParam(':name', $Clean['name']); 
//and so on 

但作爲一個個人喜好,我一直在做它像這樣

$stmt3 = $link->prepare('INSERT INTO messages VALUES(null, ?, ?, ?, ?, ?)'); 
$stmt3->execute(array($Clean['room'], $Clean['name'], $Clean['message'], $time, $Clean['color'])) 
+0

根據http://www.php.net/manual/en/pdostatement.execute.php,這是一個可選的方法,我使用的數組方法應該可以工作。 – Morgan

+0

你的第二個例子是我如何使用mysqli來做這件事,但我真的很喜歡爲了可讀性而這樣做,而且我非常喜歡這個錯誤,所以我現在很想知道是什麼原因造成的。 – Morgan

+0

-1,這個答案不太相關。 –

相關問題