Output sql query into html table

前端 未结 5 540
旧时难觅i
旧时难觅i 2021-01-16 04:52

I\'m trying to place the output of this PHP SQL query into a database table, but it is outputting all of the row data into one column.

if(isset($_POST[\'subm         


        
相关标签:
5条回答
  • 2021-01-16 04:56
    while ($row = mysql_fetch_row($result)) {
    echo '<tr>';
    foreach ($row as $value)
    {
      echo "<td>".$value."</td>";
    }
    echo "</tr>";
    }
    
    0 讨论(0)
  • 2021-01-16 05:02

    You are putting the $value inside quotation marks, it will be treated as string.

    Try:

    while ($row = mysql_fetch_row($result)) {
        echo '<tr>';
        foreach ($row as $value)
        {
          echo "<td>".$value."</td>";
        }
        echo "</tr>";
    }
    
    0 讨论(0)
  • 2021-01-16 05:02

    You need to explain the issue you're having. But from what I can see off the bat, you're looping through all the values of the row and outputting them as rows itself, instead of as a cell within the table row. The curly brackets around value are unnecessary as well, since you are concatenating the strings, you can just do '<tr><td>'.$value.'</td></tr>' OR "<tr><td>$value</td></tr>". PHP will parse variables within a string if the string is double quoted. I would also refrain from adding <br> tags as direct children of a table. If you need spacing between table rows, use padding and margins.

    0 讨论(0)
  • 2021-01-16 05:09

    try this

    while ($row = mysql_fetch_row($result)) {
    
        print "<tr><td>".$row[0]."</td></tr>";
        echo "<br>";
    }
    
    0 讨论(0)
  • 2021-01-16 05:19

    The problem is that you're outputting a <tr> tag for every row and column. You need to move the <tr> outside the inner loop.

    Technically, you don't need to concatenate "{$value}" with the other two strings, but you really should pass $value through htmlspecialchars() to avoid producing incorrect HTML if the value contains any < or & characters. Eg:

    while ($row = mysql_fetch_row($result)) {
        print '<tr>';
        foreach ($row as $value) {
            $v = htmlspecialchars ($value);
            print "<td>$v</td>";
        }
        echo "</tr>\n";
    }
    

    Also, you're not supposed to have a <br> element between table rows, which is why I replaced it with a newline above. Personally, I would skip the closing </td> and </tr> tags since they are optional in HTML.

    Note also, that the MySQL extension is deprecated and no longer maintained. You should be using MySQLi or PDO these days.

    0 讨论(0)
提交回复
热议问题