Search code examples
phpmysqlsqlmysqliforum

Displaying a list of topics with PHP, mysqli and mysqli_fetch_assoc


I am trying to make a barebones forum. I have a very simple database called talk, with a table called main, with columns called title, content, and id. $con is my connection, and I'm positive it works because I use it to insert into the database elsewhere in my code.

I am trying to display all the titles of this table, along with a link to that topics page, essentially making a topics list for my forum. Instead of giving me a table that displays each title, I get nothing. It's just blank. I've searched google and stackoverflow up and down, have found several related questions, all with wildly different solutions, but haven't found anything that works for me. I've tried a few other wordings of this code, but this seems to be the code that I think is closest to working. This should be all the code you need to see, but if you need more information, let me know.

<?php 
$sql = "SELECT 
            title,
            content,
            id 
            from main
            ORDER BY id DESC;"

if ($result = mysqli_query($con, $sql))
{
echo '<table class="table table-striped">
<tr>
<td>
<h4><strong><center>';

while($row = mysqli_fetch_assoc($result)) {
    echo '<a href="topic.php?id=' . $row['id'] . '">
    ' . $row['title'] . '</a>'

echo '</center></strong></h4>
</td>
</tr>';
}
echo '</table>';
}
?>

Thank you for your help stackoverflow.


Solution

  • Your while loop is breaking the table structure. You've started your while loop inside a "td" but ended after "tr". Here's the correct one:

    <?php 
    $sql = "SELECT title, content, id 
                from main
                ORDER BY id DESC";
    
    if ($result = mysqli_query($con, $sql))
    {
        echo '<table class="table table-striped">';
              while($row = mysqli_fetch_assoc($result)) 
              {
                  echo '<tr>
                      <td><h4><strong><center>
                          <a href="topic.php?id='.$row['id'].'">'.$row['title'].'</a>
                          </center></strong></h4>
                      </td>
                  </tr>';
              }
        echo '</table>';
    }
    ?>