【问题标题】:php echo table with while loop带有while循环的php回显表
【发布时间】:2023-03-12 11:45:01
【问题描述】:

我正在创建一个表,并希望它以某种方式布局,并且必须从数据库中检索数据。我正在尝试将其设置在顶部示例中包含用户名的位置...

吉姆·克里斯·艾伦·里克 7 8 4 5

我的代码看起来像这样,我已经搞砸了几个小时,无法弄清楚为什么我无法按照我的意愿设置它。任何帮助,将不胜感激。它是一个while循环。

   while ($pickresults= mysql_fetch_assoc($picksquery)) {
//first row                         
    echo '<th> '.$pickresults['username'].' </th> ';  
        echo ' <td> '.$pickresults['firstgame'].' </td> '; } 

【问题讨论】:

    标签: php mysql while-loop html-table


    【解决方案1】:

    先收集表头和表体,然后输出。你的做法,html是这样的,我想很容易看出html有什么问题

    <th>name</th>
    <td>value></td>
    <th>another name</th>
    <td>another value</td>
    

    你需要的是这个:

    $td = '';
    $th = '';
    while ($pickresults= mysql_fetch_assoc($picksquery)) {                      
        $th .= '<th> '.$pickresults['username'].' </th> ';  
        $td .= '<td> '.$pickresults['firstgame'].' </td> ';
    }
    echo '<table><tr>' . $th . '</tr><tr>' . $td . '</tr>' . '</table>';
    

    【讨论】:

    • 不要忘记在每一行周围加上&lt;tr&gt;,否则这将不是一个有效的&lt;table&gt;
    【解决方案2】:

    您的结构正在创建一个 TH,然后是一个 TD,然后是一个 TH,然后是一个 TD,等等。

    这不是您创建表格的方式,您首先需要制作四个 TH,然后您可以制作四个 TD。

    编辑:Marko D 提供了代码来解释我的意思。

    【讨论】:

    • 非常感谢。这很有帮助。将循环保存到数组是金钱。
    【解决方案3】:

    首先,您应该学习表格的 HTML 代码。您的代码将表头 (th) 放在普通列项 (td) 旁边。您需要先遍历标题然后下一行遍历列项或将字符串构建到echo out。

    $headers = $col = "";
    while($pickresults= mysql_fetch_assoc($picksquery)){
        $headers .= "<th> {$pickresults['username']} </th>";
        $col .= "<td> {$pickresults['firstgame']} </td>";
    }
    
    echo "<table><tr>$headers</tr><tr>$col</tr></table>";
    

    【讨论】:

      【解决方案4】:

      您需要在&lt;th&gt;-tags 中写入所有用户名。 我先把它放在一个数组中,然后从数组中放到表中……

      while ($pickresults= mysql_fetch_assoc($picksquery)) {
      
          $picked[]=$pickresults;
      
      }
      
      echo "<table><tr>"; // create table and 1st row
      
      foreach ($picked as $pick) {
      
           echo "<th>{$pick['username']}</th>"; // create 1st line headers
      
      }
      
      echo "</tr><tr>"; // close 1st row and open 2nd
      
      foreach ($picked as $pick) {
      
          echo "<td>{$pick['firstgame']}</td>"; // create 2nd line...
      
      }
      
      echo "</tr></table>"; // close 2nd row and table
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-07-02
        • 2014-12-18
        • 2017-01-30
        • 1970-01-01
        • 2012-02-25
        • 1970-01-01
        • 2023-04-10
        • 2017-07-05
        相关资源
        最近更新 更多