我一直在网上搜索解决此代码问题的可能解决方案,但没有运气。
我从代码中收到此错误:
SQLSTATE [HY093]:参数号无效:绑定变量数 与令牌数量不匹配。
见下面的代码:
<?php
// vars
$categories = array('0'=>12,'1'=>15,'2'=>17);
$values = ""; $in = "";
// re-index
if (is_array($categories))
{
$i=0;
foreach ($categories as $k => $item)
{
$i++;
$key = ':catId'.$i;
$in .= "$key,";
// collecting values into key-value array
$in_params[$key] = $item;
}
// create the IN ( :catId0,:catId1,:catId2 ) param.
// remove the last comma from the list
$in = rtrim($in,",");
$values .= " IN (" . $in . ")";
}
// Results from the above code:
// $values = IN (:catId1,:catId2,:catId3)
// $in_params = array ( [:catId1] => 12 [:catId2] => 15 [:catId3] => 17 )
$sql = "SELECT * FROM products
WHERE cat_id {$values}";
try
{
$_stmt = $this->_dbConn->prepare($sql);
foreach($in_params as $k => $val)
{
if(is_int($val)) {
$_stmt->bindValue($k,$val, PDO::PARAM_INT);
}else{
$_stmt->bindValue($k,$val);
}
}
$_stmt->execute();
foreach ($_stmt as $row)
{
// do something
}
}
catch(PDOException $e)
{
return $e->getMessage();
}
?>