0
我试图将我的旧MySQLI查询转换为PDO,同时绑定所有变量以防止注入。这个特定的查询从数组中获取它的“WHERE”条件。从数组中绑定条件变量
$w=array();
if ($pos!='') $w[]="PositionId=':pos'";
if ($country!='') $w[]="CountryId=':country'";
if ($current!='') $w[]="IsCurrent=':current'";
if ($c1stat!='') $w[]=":c1stat :c1comp ':c1val'";
if ($c2stat!='') $w[]=":c2stat :c2comp ':c2val'";
if ($c3stat!='') $w[]=":c3stat :c3comp ':c3val'";
if ($c4stat!='') $w[]=":c4stat :c4comp ':c4val'";
if (count($w)) $where="WHERE ".implode(' AND ',$w); else $where='';
$query="SELECT * FROM table $where";
$result = $pdo->prepare($query);
$result->bindParam(':pos', $pos);
$result->bindParam(':country', $country);
$result->bindParam(':iscurrent', $current);
$result->bindParam(':c1stat', $c1stat); $result->bindParam(':c1comp', $c1comp); $result->bindParam(':c1val', $c1val);
$result->bindParam(':c2stat', $c2stat); $result->bindParam(':c2comp', $c2comp); $result->bindParam(':c2val', $c2val);
$result->bindParam(':c3stat', $c3stat); $result->bindParam(':c3comp', $c3comp); $result->bindParam(':c3val', $c3val);
$result->bindParam(':c4stat', $c4stat); $result->bindParam(':c4comp', $c4comp); $result->bindParam(':c4val', $c4val);
$result->execute();
我仍然试图理解PDO和绑定变量,所以我正在努力实现这一目标。
的$查询被正确地构建,例如,一条带$国家条件语句生成:
SELECT * FROM skaterRScareer WHERE PositionId>='2' AND CountryId=':country'
那么,为什么不变量的约束? 在此先感谢!
感谢您的例子。我想我明白。 – dsol828 2013-02-27 14:04:30
您可以举一个如何将标识符列入白名单的例子吗? – dsol828 2013-02-27 14:04:55
我已经更新了我的答案。顺便说一下,它似乎你使用我的旧代码来处理条件查询:)很高兴它为你工作之前,很高兴再次帮助。如果我有时间,我会将旧代码重新导入PDO。 – 2013-02-27 14:23:45