RWN
RWN

Reputation: 99

Issue displaying SQL rows on a web page

Having difficulty displaying rows in an SQL table.

I'm trying to create a comments system for a friend's website. Everything is connected properly and the SQL database is receiving input data, as well as sending it to the web page.

I have a 'foreach' loop which I suspect is the culprit: the loop is displaying a comment with no information on it, as a result of there BEING no information on the iteration of the loop.

I'm sure there's an obvious mistake which is staring me at the face, but I can't see it.

Here's the relevant code:

    <ul>
    <?php 
        include "../include/connect.php";
        $get = mysqli_query($conn, "SELECT username, date, comment FROM comments");

        while($rows[] = mysqli_fetch_assoc($get));
        if(count($rows) > 0) {
            foreach($rows as $row) {
                $username = $row['username'];
                $date = $row['date'];
                $comment = $row['comment'];
                echo("
                    <li>
                    <article>
                      <header>
                        <figure class=\"avatar\"><img src=\"../images/demo/avatar.png\"></figure>
                        <address>
                        By <span style=\"color:lightblue;\">$username</span>
                        </address>
                        <p>$date</p>
                      </header>
                      <div class=\"comcont\">
                        <p>$comment</p>
                      </div>
                    </article>
                  </li>
                ");
            }
        }
    ?>

    </ul>

The web page we're trying to deal with is here:

http://lenslord.co.uk/pages/Testimonials.php

Any help will be greatly appreciated!

Upvotes: 1

Views: 59

Answers (2)

random_user_name
random_user_name

Reputation: 26160

You've introduced some complexity that is unnecessary, and is likely the cause for the issues you are facing.

From your current code:

while( $rows[] = mysqli_fetch_assoc($get) ) {

Gets a single row from the database, and adds it to an unknown index in the $rows variable. This while will run as many times as there are rows in the result set.

Then:

    if( count($rows) > 0) {

Says "if there are any records in the $rows array. We know there are, because you just put one in there.

Then:

        foreach( $rows as $row ) {

Says "loop over all the records in the $rows array. This is also unnecessary, and is causing complexity.

This should be simplified to just be:

 while( $row = mysqli_fetch_assoc( $get ) ) {
    $username = $row['username'];
    $date = $row['date'];
    // ... etc
 }

Upvotes: 4

Funk Forty Niner
Funk Forty Niner

Reputation: 74217

As stated in comments, don't use a while and a foreach.

Use one or the other, not both.

Magnus suggested:

while($row = mysqli_fetch_assoc($get)) { ...all your code that's currently inside the foreach... }

Upvotes: 3

Related Questions