dongliuzi3410
2015-02-03 05:54
浏览 42
已采纳

Mysqli预处理语句:将行存储在数组中,稍后循环遍历此数组

I use a prepared statement to select rows in a database. Subsequently I would like to echo the individual rows using a while loop. This worked fine, until I tried using a new query within the execution of the while loop (this was necessary because I extract the userID, which I need to transform into a username. I did this by performing a query on the users table, but when I try this, my code doesn't run). I thought I might fix this by storing all the rows in an array, and later in my code loop through this array. However, I can't seem to figure out how to loop through all indices of this array and extract all fields of the row in each instance of the loop.

Thanks a lot! Here is my code:

$results = array();

$stmt = $db->prepare("SELECT admissionID,userID,description,link,postingdate,compensation FROM replies WHERE projectID=?");
$stmt->bind_param('i',$projectID);
$stmt->execute();
$stmt->bind_result($admissionID,$userID,$description,$link,$postingdate,$compensation);
while($row = $stmt->fetch()){
    $results[] = $row;
}

foreach($results as $result) {
    echo $result['admissionID'];
}
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duanran6441 2015-02-03 05:59
    已采纳

    This is how you need to do it

     ids=array();
     while($row = $stmt->fetch()){
        ids[]= $row['userID'];
     }
    

    ids is an array and will have all the ids that you need. But I would say "Dont do it like that", just use a table join to get the username for example may be your case would be like

    SELECT   replies.admissionID,users.name,replies.userID,replies.description,
    replies.link,replies.postingdate,replies.compensation FROM replies, users 
    WHERE 
    users.name=replies.userID
    and replies.projectID=?
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题