【发布时间】:2014-02-15 20:05:21
【问题描述】:
我花了很多时间试图找出这里出了什么问题,我很难过。 这是失败的特定 PHP 代码:
//Handy function I use to do all my bound queries - yes you can have it.
function prepareBindAndExecute($pdo, $qry, $aParams) {
if (!$stmt = $pdo->prepare($qry)) {
setSessionError("Failed to prepare $qry");
return false;
}
foreach ($aParams as $aParam) {
// $aParam[0] = ":labelToBind"
// $aParam[1] = value to Bind
// $aParam[2] = PDO::PARAM_TYPE
if (strpos($qry, $aParam[0]) !== false) { // skip binding if label isn't in query. This allows built up queries to not fail if parts were not created for a parameter.
if (!$stmt->bindParam($aParam[0], $aParam[1], $aParam[2])) {
setSessionError("Failed to bind $aParam[1] as $aParam[0] to $qry Error Info:".print_r($stmt->errorInfo()));
return false;
}
}
}
if (!$stmt->execute()) {
setSessionError("Failed to execute $qry bound with ".json_encode($aParams).' Error Info:'.print_r($stmt->errorInfo()));
return false;
}
return $stmt;
}
// Here's the problem call: The member_login is a VARCHAR(32) receiving an email address string
// and the submission_date is a DateTime column receiving the current date.
$stmt = prepareBindAndExecute($pdoRW,
'INSERT INTO videosubmissions (member_login, submission_date) VALUES (:login, :submission-date)',
[ [ ':login', $info['login'], PDO::PARAM_STR ],
[ ':submission-date', $submission_date->format(DateTime::ISO8601), PDO::PARAM_STR ] ]);
这是我使用这段代码得到的结果:
执行失败
INSERT INTO videosubmissions (member_login, submit_date) VALUES (:login, :submission-date) 绑定 [[":login","xTst2@gmail.com",2], [":提交日期","2014-02-15T20:37:01+0100",2]]
在错误日志中有一个相关的PHP错误:
PHP 警告:PDOStatement::execute(): SQLSTATE[HY093]: 无效参数 number: 参数未在...中定义
这个简单的情况不是参数数量不匹配的情况,因为只有两个标签要绑定。我的辅助函数一直在处理比这个更复杂的查询。 有一段时间我以为我通过引用 :label tag -> VALUES (":label", :submission_date ... 这让调用成功,但导致刺痛“:标签”被插入数据库,事实上,据我了解,会导致真正的参数计数不匹配。 PDO::PARAM_ 常量不提供 DATE 或 DATETIME 风格。 (见http://www.php.net/manual/en/pdo.constants.php) 我已经验证我的辅助函数没有跳过绑定任何参数 - 我们可以从返回的错误消息中播种。
我还尝试将 submit_date 与 DateTime PHP 对象而不是字符串绑定,并且我尝试了各种数据/时间格式的字符串。 我想知道登录参数中的 @ 是否以某种方式破坏了绑定。 如果 PDO 能提供发送到 mySql 的实际查询,那就太好了,但这可能隐藏在驱动程序中。
希望我只是错过了一些愚蠢的东西。 谢谢!!!
【问题讨论】:
-
是否使用
bindValue代替bindParam修复它? -
尝试使用
:submission_date而不是:submission-date。或?作为占位符。