我已经在这段代码上扯了几个小时...... 对我来说没有意义,为什么它不起作用
$isCorrect =($question->correct_answer == $body->answer) ? 1:0;
// the values are all there.......
// echo $body->question . "\n"; //335
// echo $body->user . "\n"; //51324123
// echo $question->day . "\n"; //0
// echo $isCorrect . "\n"; //0
//but still the below part fails.
$db = getConnection();
$sql = "INSERT INTO `answers` (`id`, `question_id`, `user`, `day`, `is_correct`) VALUES (NULL, ':question', ':user', ':day', :is_correct)";
$stmt = $db->prepare($sql);
$stmt->bindParam(":question_id", $body->question);
$stmt->bindParam(":user", $body->user);
$stmt->bindParam(":day", $question->day, PDO::PARAM_INT);
$stmt->bindParam(":is_correct", $isCorrect, PDO::PARAM_INT);
$stmt->execute();
给出了这个错误:
SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
我正在计算4个代币......我错过了什么?显然,我做错了什么。
答案 0 :(得分:2)
试试这样:
$sql = "INSERT INTO `answers` (`id`, `question_id`, `user`, `day`, `is_correct`)
VALUES
--The :variable shouldn't be surrounded by ''--
(NULL, :question, :user, :day, :is_correct)";
$stmt = $db->prepare($sql);
//The values used in $sql should be the same here, so not :question_id but :question
$stmt->bindParam(":question", $body->question);
$stmt->bindParam(":user", $body->user);
$stmt->bindParam(":day", $question->day, PDO::PARAM_INT);
$stmt->bindParam(":is_correct", $isCorrect, PDO::PARAM_INT);
答案 1 :(得分:1)
不要将bindParam与PDO一起使用 以及命名参数。它会为你节省大量的麻烦
$db = getConnection();
$sql = "INSERT INTO `answers` VALUES (NULL, ?,?,?,?)";
$data = [$body->question,$body->user,$question->day,$isCorrect];
$stmt = $db->prepare($sql)->execute($data);
答案 2 :(得分:0)
改变:
$stmt->bindParam(":question_id", $body->question);
为:
$stmt->bindParam(":question", $body->question);
您在查询:question
中使用,但绑定了错误的密钥(:question_id
)。
答案 3 :(得分:0)
$stmt->bindParam(":question_id", $body->question);
应该是
$stmt->bindParam(":question", $body->question);
这只是一个小错字。