2011-12-08 80 views
0

我有一些在php中插入查詢的麻煩,由於某些原因失敗。我已經迴應了這些變量,他們確實有相同之處。PHP PDO準備插入。爲什麼這會失敗?

$query = "INSERT into thrives (n_emp, comment, g_emp) VALUES (':n_emp', ':comment', ':g_emp')"; 
$db -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 

$statement = $db -> prepare($query); 
$statement -> bindValue(':n_emp', $name, PDO::PARAM_INT); 
$statement -> bindValue(':comment', $comment, PDO::PARAM_STR); 
$statement -> bindValue(':g_emp', $_SESSION['emplid'], PDO::PARAM_INT); 
$result = $statement -> execute(); 
$statement -> closecursor(); 

我將輸出傳遞給alertbox,這就是我得到的結果。

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens' in /Applications/XAMPP/xamppfiles/htdocs/jen/maintabs/submit.php:33 
Stack trace: 
#0 /Applications/XAMPP/xamppfiles/htdocs/jen/maintabs/submit.php(33): PDOStatement->execute() 
#1 {main} 
    thrown in /Applications/XAMPP/xamppfiles/htdocs/jen/maintabs/submit.php on line 33 

有人看到我哪裏出錯了嗎?

更新1

我加入了'在前面:評論,這是新的錯誤消息

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`login`.`thrives`, CONSTRAINT `thrives_ibfk_1` FOREIGN KEY (`n_emp`) REFERENCES `employees` (`ID`))' in /Applications/XAMPP/xamppfiles/htdocs/jen/maintabs/submit.php:33 
Stack trace: 
#0 /Applications/XAMPP/xamppfiles/htdocs/jen/maintabs/submit.php(33): PDOStatement->execute() 
#1 {main} 
    thrown in <b>/Applications/XAMPP/xamppfiles/htdocs/jen/maintabs/submit.php</b> on line <b>33</b><br /> 

回答

4

從綁定參數刪除引號。它應該是INSERT into thrives (n_emp, comment, g_emp) VALUES (:n_emp, :comment, :g_emp)。單引號使其成爲字面字符串。

0

引號不應用於SQL中的佔位符。請嘗試以下內容作爲您的SQL字符串:

INSERT into thrives (n_emp, comment, g_emp) VALUES (:n_emp, :comment, :g_emp);