2014-04-11 73 views
0

我一直在抓我的头在此代码为几个小时.... 没有道理给我,为什么它不工作使用bindParam与PDO

$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

有参数无效的数字,因为你把你的命名参数在单引号,这是不是这样做的方式。命名参数':question'不能放在单引号中,比'?' –

回答

0

变化:

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

到:

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

您在查询:question使用,但用错了键(:question_id)结合。

+0

比我快(:) – zkanoca

+0

@springbo别忘了接受它:)如果有帮助 –

+0

非常感谢你们两位!令人惊讶的是,我完全睁大眼睛盯着它。 我会尽快接受这个答案。 再次感谢! – springbo

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

应该

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

这只是一个小错字。

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); 
+0

我只是想要学习。为什么不应该使用bindParam?是否有漏洞? – zkanoca

+0

只是比较一下代码量 –

+0

很好的建议。谢谢。 – springbo

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); 
+0

Ahaha唯一的眼睛发现错误 –