PHP PDOException:“;SQLSTATE[HY093]:参数编号无效;
当我尝试运行以下函数时,出现错误“SQLSTATE[HY093]:参数编号无效”:PHP PDOException:“;SQLSTATE[HY093]:参数编号无效;,php,mysql,pdo,Php,Mysql,Pdo,当我尝试运行以下函数时,出现错误“SQLSTATE[HY093]:参数编号无效”: function add_persist($db, $user_id) { $hash = md5("per11".$user_id."sist11".time()); $future = time()+(60*60*24*14); $sql = "INSERT INTO persist (user_id, hash, expire) VALUES (:user_id, :hash, :e
function add_persist($db, $user_id) {
$hash = md5("per11".$user_id."sist11".time());
$future = time()+(60*60*24*14);
$sql = "INSERT INTO persist (user_id, hash, expire) VALUES (:user_id, :hash, :expire) ON DUPLICATE KEY UPDATE hash=:hash";
$stm = $db->prepare($sql);
$stm->execute(array(":user_id" => $user_id, ":hash" => $hash, ":expire" => $future));
return $hash;
}
我觉得这是一件简单的事情,我只是不明白。有什么想法吗?试试:
$sql = "INSERT INTO persist (user_id, hash, expire)
VALUES (:user_id, :hash, :expire)
ON DUPLICATE KEY UPDATE hash=:hash2";
及
摘自文档():
调用PDOStatement::execute()时,必须为要传递到语句中的每个值包含一个唯一的参数标记。在准备好的语句中,不能两次使用同名的命名参数标记。不能将多个值绑定到单个命名参数,例如SQL语句的in()子句
这是使用PDO的一个限制。PDO只需确认查询和执行中的参数数量,并在任何不匹配时抛出错误。如果需要在查询中使用参数重复,则必须使用变通方法
$sql = "insert into persist(user_id, hash, expire) values
(:user_id, :hash, :value) on duplicate key update
hash = :hash2";
$stm->execute(array(':user_id' => $user_id, ':hash' => $hash, ':hash2' => $hash,
':expire' => $expire));
您可以参考这篇文章来了解更详细的解决方法-我知道这是一个老问题,但我认为值得注意的是,更合适的解决方案是通过适当利用SQL避免PHP中繁琐的解决方法:
INSERT INTO `persist` (`user_id`, `hash`, `expire`)
VALUES (:user_id, :hash, :expire)
ON DUPLICATE KEY UPDATE `hash`=VALUES(`hash`)
这样,您只需要发送一次值。
您不能在准备好的语句中两次使用同名的命名参数标记。
我知道那篇文章的答案也回答了我的问题,但我的问题肯定不可能重复。在另一个问题中,fetchAll()
不返回任何内容,因为查询与您的查询一样失败。另一位作者只是没有注意到。这基本上是同一个问题,因此值得将这两个问题联系起来。是的,它们联系在一起的原因是答案是相同的,但是没有办法根据问题知道这一点!只要斯塔克允许,我就接受你的回答。为什么原始方法不起作用?@VijayRamamurthy,请通读以下内容:你的答案和OP的问题有什么区别?太棒了!我花了两天的时间调试代码,除了一个特定的查询之外,其他所有的代码都可以工作。答案是(正如上面“vijrox”在评论中提到的),您不能在PDO中重用相同的命名参数。我让updateusers设置username=:username,caption=:caption其中username=:username
,这将不起作用,因为:username
出现两次。修复方法是重命名第二个,结果是:更新用户集username=:username,caption=:caption,其中username=:user
(最后一个:user
不同)。虽然此代码可能有助于解决问题,但它没有解释为什么和/或如何回答问题。提供这种额外的环境将大大提高其长期教育价值。请在回答中添加解释,包括适用的限制和假设。
$stmt = $con->prepare("INSERT INTO items(Name, Description, Price, Country_Made, Status, Add_Date) VALUES( :zname, :zdesc, :zprice, :zcountry, zstatus, now())");
$stmt-> execute(array(
"zname" => $name,
"zdesc" => $desc,
"zprice" => $price,
"zcountry" => $country,
"zstatus" => $status
));
INSERT INTO `persist` (`user_id`, `hash`, `expire`)
VALUES (:user_id, :hash, :expire)
ON DUPLICATE KEY UPDATE `hash`=VALUES(`hash`)