PHP 使用多个 while 循环仅检索 1 行

标签 php mysql pdo while-loop

目前,我的计划是在用户名旁边添加性别图标。问题是,即使表中有超过1条表记录,它也只显示1行,并且有些记录突然消失了。它是这样的:

我正在使用的代码:

$pdo = new PDO('connection');  
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$stmt1 = $pdo->prepare("SELECT id, user_id, user, bid, date
FROM auction_bids ORDER BY date DESC");  
$stmt2 = $pdo->prepare("SELECT user_id, user, bid, date
FROM auction_bids ORDER BY date DESC LIMIT 30");
$stmt11 = $pdo->prepare("SELECT pol FROM tb_users WHERE id = :user_id");

$stmt2->execute();
$r1 = $stmt1->fetch(PDO::FETCH_ASSOC);
$stmt11->execute(array(':user_id' => $r1['user_id']));

$id1 = $r1['id'];
echo '<table>';
while ($r1 = $stmt2->fetch(PDO::FETCH_ASSOC) && $r2 = $stmt11- >fetch(PDO::FETCH_ASSOC)) {
  echo '<tr>
        <td>' . $id1 . '</td>
        <td><img height="16" width="16" alt="gender icon" src
                ="../images/' . ($r2['pol'] == 1 ? 'male.png' : 'female.png') . '" />
        ' . $r1['user'] . '</td>
        <td class="border-right">' . $r10['level'] . '</td>
        <td>' . $r1['bid'] . ' FA</td>
        <td><img height="16" width="16" alt="calendar" src
                ="../images/calendar.png" />
            ' . date($dateFormatBids, strtotime($r1['date'])) . '</td>
        </tr>
  ';
  $id1--;
}
echo '<table>

使用 while ($r1 = $stmt2->fetch(PDO::FETCH_ASSOC)) {..} 循环而不使用 $r2,它正在工作(除了性别颜色相同,对于测试,它应该是红色,对于卢卡斯,应该是蓝色):

如果有什么需要,请说。我对 PHP 和 PDO 还很陌生。

最佳答案

从行: $stmt11->execute(array(':user_id' => $r1['user_id'])); 您将获得一条记录,因此 while 循环打印一条记录行。

编写如下查询:

$stmt2 = $pdo->prepare("SELECT tu.pol, user_id, user, bid, date 
FROM auction_bids ab left join tb_users tu on ab.user_id = tu.id
ORDER BY date DESC LIMIT 30");

现在:

while ($r1 = $stmt2->fetch(PDO::FETCH_ASSOC){
    //rest of the code should work... user $r1['pol'] instead of $r2
}

关于PHP 使用多个 while 循环仅检索 1 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39063522/

相关文章:

mysql - Django 窗体性能

php - PHP PDO 语句可以接受表名或列名作为参数吗?

php - PDO 分页不显示错误也不输出

php - 当您只进行一次选择时,使用准备好的 Select 语句是否更好?

php - Oauth2有没有Php客户端?

php - file_get_contents 替代函数或方法?

php - Nginx 的 WordPress HTTPS (SSL) 永久链接配置

php - LinkedIn Share API 'ugcPosts' 响应 504 PHP 网关超时(WordPress)

c# - 如何从防火墙后面连接到 MySQL?

MySQL 使用 = 无法正确匹配电子邮件地址,但可以使用 LIKE