PDO bindParam()PHP Foreach循环 [英] PDO bindParam() PHP Foreach Loop

查看:91
本文介绍了PDO bindParam()PHP Foreach循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个foreach循环,我想执行一个prepare语句pdo.我已经阅读了几篇有关参考的文章,但我不知道该如何使用我的代码:

I have a foreach loop that I would like to execute a prepare statement pdo. I have read a few posts on making a reference but I do not know how to do it with my code:

$str = ":City, Aurora; :State, CO";
$wherestr = explode(";",$str);

$sql = "SELECT * FROM Organization WHERE City = :City AND State= :State";
$stmt = $db->prepare($sql);

foreach ($wherestr as $ws) {
 $ws = explode(",",$ws);
 $ws0 = trim($ws[0]);
 $ws1 = trim($ws[1]);
 $stmt->bindParam($ws0,$ws1);
}
$stmt->execute();

我在这里已阅读循环内PDO语句的绑定参数,您可以通过使用&创建引用来完成这项工作.符号,但是我没有像他们一样使用Key => Value.谁能帮助我让它遍历参数并执行?

I have read here Binding params for PDO statement inside a loop that you can make this work by creating a reference with the & symbol but I am not using a Key=>Value like they are. Can anyone help me get this to loop through the Param and execute?

如果我只有一个WHERE(:var),那么它可以正常工作,但是如果我有多个WHERE过滤器,则它似乎会覆盖以前的过滤器,而不是执行execute语句中的所有bindParams.我没有任何错误,只是没有使用多个变量正确过滤结果.

If i only have one WHERE (:var) then it works fine but if i have multiple WHERE filters than it seems to override the previous filter instead of executing all of the bindParams in the execute statement. I don't get any errors it just doesn't filter the results properly with more than one var.

谢谢.

推荐答案

您应像这样使用bindParam:

$sql = 'SELECT * FROM Organization WHERE City = :City AND State= :State';
$wherestr = array('string1', 'string2');
$stmt = $db->prepare($sql);
$stmt->bindParam(':City', $wherestr[0]);
$stmt->bindParam(':State', $wherestr[1]);
$stmt->execute();

如果您坚持使用foreach,请使用以下方法:

if you insist using foreach, here is a way:

$stmt = $db->prepare($sql);
$params = array(':City' => 'string1', ':State' => 'string2');
foreach ($params as $key => &$val) {
    $stmt->bindParam($key, $val);
}
$stmt->execute();

请注意,我们必须在循环中使用通过引用传递,这是必须的.

note that we use pass by reference in the loop, which is a must.

这篇关于PDO bindParam()PHP Foreach循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆