Mysqli 准备语句:将行存储在一个数组中,稍后循环遍历该数组
Mysqli prepared statement: store rows in an array and loop through this array later
我对数据库中的 select 行使用准备好的语句。随后,我想使用 while 循环回显各个行。这工作正常,直到我尝试在 while 循环的执行中使用新查询(这是必要的,因为我提取了用户 ID,我需要将其转换为用户名。我通过对用户执行查询来做到这一点 table,但是当我尝试这个时,我的代码没有 运行)。我想我可以通过将所有行存储在一个数组中来解决这个问题,然后在我的代码中循环遍历这个数组。但是,我似乎无法弄清楚如何遍历该数组的所有索引并在每个循环实例中提取该行的所有字段。
非常感谢!这是我的代码:
$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'];
}
这就是您需要的方式
ids=array();
while($row = $stmt->fetch()){
ids[]= $row['userID'];
}
ids 是一个数组,将包含您需要的所有 ID。
但我会说 "Dont do it like that",只需使用 table 连接来获取用户名,例如你的情况可能是
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=?
我对数据库中的 select 行使用准备好的语句。随后,我想使用 while 循环回显各个行。这工作正常,直到我尝试在 while 循环的执行中使用新查询(这是必要的,因为我提取了用户 ID,我需要将其转换为用户名。我通过对用户执行查询来做到这一点 table,但是当我尝试这个时,我的代码没有 运行)。我想我可以通过将所有行存储在一个数组中来解决这个问题,然后在我的代码中循环遍历这个数组。但是,我似乎无法弄清楚如何遍历该数组的所有索引并在每个循环实例中提取该行的所有字段。
非常感谢!这是我的代码:
$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'];
}
这就是您需要的方式
ids=array();
while($row = $stmt->fetch()){
ids[]= $row['userID'];
}
ids 是一个数组,将包含您需要的所有 ID。 但我会说 "Dont do it like that",只需使用 table 连接来获取用户名,例如你的情况可能是
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=?