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=?
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀