using bindParam with PDO

南笙酒味 提交于 2020-01-06 07:07:50

问题


I've been scratching my head over this code for a couple of hours.... Doesn't make sense to me why it doesn't work

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

gives this error:

SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens

I'm counting 4 tokens... what am I missing? Obviously I'm doing something wrong.


回答1:


change :

$stmt->bindParam(":question_id", $body->question);

to:

$stmt->bindParam(":question", $body->question);

You have use in query :question but binding with wrong key(:question_id).




回答2:


Try it like this:

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



回答3:


just don't use bindParam with PDO
as well as named parameters. it will save you a ton of headaches

$db = getConnection();
$sql = "INSERT INTO `answers` VALUES (NULL, ?,?,?,?)";
$data = [$body->question,$body->user,$question->day,$isCorrect];
$stmt = $db->prepare($sql)->execute($data);



回答4:


$stmt->bindParam(":question_id", $body->question);

should be

$stmt->bindParam(":question", $body->question);

This is just a little typo.



来源:https://stackoverflow.com/questions/23013463/using-bindparam-with-pdo

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!