我正在尝试从数据库中获取查询,但是当我回显bindParam
和(:name)
时,我对$sql
print_r($stmtTwo)
的值没有受到限制WHERE
子句指出WHERE :name
而不是来自$wherefinal
的字符串。
我的代码是:
$sql= "SELECT Species.Species_ID
FROM Species
JOIN (
SELECT Species.Species_ID, COUNT(*) AS mynum
FROM Species_Opt LEFT JOIN Species ON (Species.Species_ID = Species_Opt.SO_Species_ID)
WHERE :name
GROUP BY SO_Species_ID HAVING mynum = 6
) AS mytable ON Species.Species_ID = mytable.Species_ID";
$stmtTwo = $pdo->prepare($sql);
$stmtTwo->bindParam(':name', $wherefinal);
$stmtTwo->execute();
在sql语句之前定义$wherefinal
并定义为:
$where = "";
foreach ($_POST as $k => $v){
$where .= "(Species_Opt.SO_Option_ID = $v) OR ";
};
$wherefinal = substr($where, 0, strrpos($where, " OR "));
当回显时,$wherefinal
显示:
(Species_Opt.SO_Option_ID = 4) OR (Species_Opt.SO_Option_ID = 12) OR (Species_Opt.SO_Option_ID = 17) OR (Species_Opt.SO_Option_ID = 20) OR (Species_Opt.SO_Option_ID = 21) OR (Species_Opt.SO_Option_ID = 32)
$v
来自通过不同的SQL语句生成的表单中的单选按钮的值。
答案 0 :(得分:0)
首先,您需要构建占位符部分
$placeholder = str_repeat('?,', count($_POST) - 1) . '?';
然后使用它来构建完整的SQL查询
$sql= "SELECT Species.Species_ID
FROM Species
JOIN (
SELECT Species.Species_ID, COUNT(*) AS mynum
FROM Species_Opt LEFT JOIN Species ON
(Species.Species_ID = Species_Opt.SO_Species_ID)
WHERE Species_Opt.SO_Option_ID IN ({$placeholder})
GROUP BY SO_Species_ID HAVING mynum = 6
) AS mytable ON Species.Species_ID = mytable.Species_ID";
之后,您可以将值绑定到每个占位符
$sh = $pdo->prepare($sql);
$i = 1;
foreach($_POST as $value) {
$sh->bindValue($i, $value); $i++;
}
$sh->execute();