PHP PDO准备插入。为什么这会失败?

时间:2011-12-08 21:12:20

标签: php mysql

我在php中使用插入查询遇到了一些问题,由于某种原因它失败了。我已经回应了变量,他们确实有所不同。

$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();

我将输出传递给警告框,这就是我得到的。

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

我在前面添加了'comment:comment,这是新的错误消息

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 />

2 个答案:

答案 0 :(得分:4)

从绑定参数中删除引号。它应该是INSERT into thrives (n_emp, comment, g_emp) VALUES (:n_emp, :comment, :g_emp)。单引号使其成为文字字符串。

答案 1 :(得分:0)

引号不应该应用于SQL中的占位符。请尝试以下SQL字符串:

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