在循环中使用计数器和数组进行多次提取

4
我一直在使用PDO中的bindParam()方法执行准备好的查询时遇到了问题。基本上我想做的是循环遍历一个数组,并且返回数据库中每个数组元素的数据。现在我意识到bindParam()方法应该将变量绑定到查询语句中,但是这对数组是如何起作用的呢?因为我无法似乎使其工作:S
以下是我的代码:
<?php
    $i = 0;
    $statement = $conn->prepare("SELECT * FROM users WHERE id = :id");
    $statement->bindParam(":id", $friendListIDs[$i], PDO::PARAM_STR);
    $friendListIDs = explode($details['friends'], " ");
    while($i <= count($friendListIDs))
    {
          $statement->execute();
          $row = $statement->fetch();
          echo "<img src='../img/friend_icon.png' alt='' align='left' />
                <span>
                <a href='#'>".$row['firstname']." ".$row['surname']."</a>
                <br />
                <a href='#'>100% wishes fulfilled</a>
                </span><br /><br />";
                $i++;
    }   
?>

1
在 while 循环内尝试使用 $statement->bindParam(":id", $friendListIDs[$i], PDO::PARAM_STR); - user800014
1
这里有一个小提示:如果你在一个 select 语句中获取所有结果,然后在 PHP 中迭代返回的值,你将获得更好的性能。对于相同数量的数据来说,减少了往返次数。 - databyss
1个回答

2

与其使用 bindParam,你可以向 $statement->execute 添加一个数组参数,如下所示:

$statement->execute(array(":id"=>$friendListIDs[$i]));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接