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

报告相同问题?

悬赏问题

  • ¥30 Windows Server 2016利用兩張網卡處理兩個不同網絡
  • ¥15 Python中knn问题
  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源