2012-07-27 56 views
4

我一直有一個問題在循環中使用bindParam()與PDO執行準備好的查詢。基本上我想要做的是循環一個數組,並與每個數組元素,從數據庫中返回數據。現在我意識到 - > 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

嘗試'$ statement-> bindParam(「:id」,$ friendListIDs [$ i],PDO :: PARAM_STR);'while while。 – 2012-07-27 00:53:18

+1

注意這裏:如果您在一次選擇中獲得所有結果,您將獲得更好的性能,然後遍歷php中的返回值。相同數據量的往返次數減少。 – databyss 2012-07-27 01:45:51

回答

2

而不是使用bindParam你可以這樣一個數組參數添加到$statement->execute

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