gpt4 book ai didi

php - 警告:PDOStatement::execute(): SQLSTATE[HY093]: 参数编号无效:绑定(bind)变量的数量与中的标记数量不匹配

转载 作者:可可西里 更新时间:2023-11-01 13:00:35 24 4
gpt4 key购买 nike

我正在使用 PHP PDO,但遇到以下问题:

Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens in /var/www/site/classes/enterprise.php on line 63

这是我的代码:

    public function getCompaniesByCity(City $city, $options = null) {
$database = Connection::getConnection();

if(empty($options)) {
$statement = $database->prepare("SELECT * FROM `empresas` WHERE `empresas`.`cidades_codigo` = ?");
$statement->bindValue(1, $city->getId());
}
else {
$sql = "SELECT * FROM `empresas`
INNER JOIN `prods_empresas` ON `prods_empresas`.`empresas_codigo` = `empresas`.`codigo` WHERE ";

foreach($options as $option) {
$sql .= '`prods_empresas`.`produtos_codigo` = ? OR ';
}

$sql = substr($sql, 0, -4);
$sql .= ' AND `empresas`.`cidades_codigo` = ?';

$statement = $database->prepare($sql);

echo $sql;

foreach($options as $i => $option) {
$statement->bindValue($i + 1, $option->getId());
}

$statement->bindValue(count($options), $city->getId());
}

$statement->execute();

$objects = $statement->fetchAll(PDO::FETCH_OBJ);
$companies = array();

if(!empty($objects)) {
foreach($objects as $object) {
$data = array(
'id' => $object->codigo,
'name' => $object->nome,
'link' => $object->link,
'email' => $object->email,
'details' => $object->detalhes,
'logo' => $object->logo
);

$enterprise = new Enterprise($data);
array_push($companies, $enterprise);
}

return $companies;
}
}

最佳答案

看起来您正在尝试构建一个长(?)系列的“或”比较:if (x=1) or (x=2) or (x=3) etc...。您可能会发现将其替换为:

$cnt = count($options);
if ($cnt > 0) {
$placeholders = str_repeat(', ?', $cnt - 1);
$sql .= 'WHERE '`prods_empresas`.`produtos_codigo` IN (?' . $placeholders . ')';
}

如果有 5 个选项,你会得到

 WHERE prods_empresas.produtos_condigo IN (?, ?, ?, ?, ?)

然后将值绑定(bind)到:

$pos = 1;
foreach ($options as $option) {
$statement->bindValue($pos, $option->getId());
$pos++
}

关于php - 警告:PDOStatement::execute(): SQLSTATE[HY093]: 参数编号无效:绑定(bind)变量的数量与中的标记数量不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2713566/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com