【问题标题】:Mulitple Fetches in Loop using Counter and Array使用计数器和数组在循环中多次获取
【发布时间】:2012-07-25 16:13:31
【问题描述】:

我在循环中使用带有 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++;
    }   
?>

【问题讨论】:

  • 尝试$statement-&gt;bindParam(":id", $friendListIDs[$i], PDO::PARAM_STR);在while内。
  • 这里的旁注:如果您在一次选择中获得所有结果,然后遍历 php.ini 中的返回值,您将获得更好的性能。相同数据量的往返次数更少。

标签: php mysql loops pdo fetch


【解决方案1】:

您可以像这样向$statement-&gt;execute 添加数组参数,而不是使用bindParam

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-10
    • 2020-11-14
    • 1970-01-01
    • 1970-01-01
    • 2019-06-06
    • 1970-01-01
    相关资源
    最近更新 更多