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

时间:2016-08-21 11:10:20

标签: 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)) {..}的{​​{1}}循环,它正在工作(除了性别颜色相同,测试它应该是红色,对于Lukas,应该是蓝色):

如果你需要什么,请说。我是PHP和PDO的新手。

2 个答案:

答案 0 :(得分:1)

从行:$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
}

答案 1 :(得分:0)

检查链接以了解while循环: http://www.w3schools.com/js/js_loop_while.asp

你有条件的问题应该为TRUE,并且你($ r1&amp;&amp; $ r2)= TRUE只有当两个变量都为TRUE时,$ r2第一次它为TRUE,第二次才会变为FALSE。 / p>

你应该只循环$ r1并在循环中调用$ r1。