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 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化