PHP while 循环和表

标签 php while-loop html-table

我无法将其放入一张表中。现在我正在使用两张 table 并将它们并排放置,但我认为这不是最好的解决方案。我已经把 table 都准备好了,但我只是不知道如何把它变成一个。

while ($row = mysql_fetch_assoc($query)) {

$result .= "<tr> <td> {$row['a']} the {$row['b']} </td>      </tr>";
 }

  echo $thegames;

这会产生如下内容:

       james the giant
       rick the monster
       chris the goblin

我想要的是能够从单独的 while 循环添加更多 tds...

  while($secondrow = mysql_fetch_assoc($secondquery)) { 
   $first = "<td> {$secondrow['alias']} </td>";
   $second = "<td> {$secondrow['number']} </td>";
  }

所以最后我希望它看起来像这样:

   james the giant $secondrow['alias']  $secondrow['number'] 
   rick the monster $secondrow['alias']  $secondrow['number']

等等...

希望这是有道理的。我现在正在做的是创建两个单独的表并尝试将它们排列起来,但不喜欢这种方法。任何帮助都会很棒。

最佳答案

从您的代码来看,您实际上不需要执行两个查询。如果您期望每行 4 列,则也无需执行多个 while 循环。相反,更改查询结构以使用 JOIN;这将使您能够一次性获得完整的结果集。

正如已经提到的,请不要在新代码中使用 mysql_* 函数。它们不再被维护并被正式弃用。

我将向您展示如何使用 PDO 进行 JOIN,并根据您目前展示的代码对表名和主键做出一些假设:

$pdo = new PDO("mysql:host=localhost;dbname=database", '-username-', '-password-');
$sql = '
    SELECT 
        `players`.`id`, 
        `players`.`a`,
        `players`.`b`, 
        `player_info`.`alias`,
        `player_info`.`number`   
    FROM 
        `players` 
    LEFT JOIN
        `player_info` ON  `players`.id = `player_info`.`player_id`
';
$players = $pdo->query($sql);

$row_data= array();
while ($row = $players->fetch()) {
    $row_data[] = '
        <td>'.$row->a.' the '.$row->b.'</td>
        <td>'.$row->alias.'</td>
        <td>'.$row->number.'</td>   
    ';
}

echo '<table><tr>'.implode('</tr><tr>', $row_data).'</tr></table'>;

如果连接被证明不切实际(不典型),那么您应该构建数据数组并生成 HTML,分为两个单独的步骤:

// gather the data
$data = array();
$first = $pdo->query($sql);
while($arow = $first->fetch()) {
    $one_data['a'] = $arow->a;
    $one_data['b'] = $arow->b;

    $second = $pdo->query($second_sql);
    while($brow = $second->fetch()) {
        $one_data['alias'] = $brow->alias;
        $one_data['number'] = $brow->number;
    }
    $data[] = $one_data;
}

// now generate HTML
print '<table>';
foreach ($data as $row) {
    print '
        <tr>
            <td>'.$row['a'].' the '.$row['b'].'</td>
            <td>'.$row['alias'].'</td>
            <td>'.$row['number'].'</td> 
        </tr>
    ';
}
print '</table>';

顺便说一句...名为 ab 的列只是一个想法。这些列代表数据,因此请为它们提供反射(reflect)数据内容的标签。今天处理神秘专栏可能没问题……你记得它们的意思。 6个月后?一年后?为所有列和变量使用有意义的名称——为什么不呢?

文档

关于PHP while 循环和表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15837660/

相关文章:

ruby - 你如何在 Ruby 中循环遍历多行字符串?

php - 你能相信 mysql_insert_id 吗?

php - 如何设置phpmyadmin的用户名和密码

java - Java 回文 : While and If/Else Statements

html - 使 HTML 表格单元格优先于其他单元格

javascript - 列中的 Jquery Keyup

html - CSS 表 : bottom borders that don't touch and rounded corners

php - 使用php在不同的sql表中导入csv文件的选定列

c# - 实体/LINQ/ASP.NET : ASPxGridView Adding Rules

具有混合条件的 bash while 循环