I seem to be having a problem getting this while() loop to work...

include("database_connect.php");

$query = "SELECT id, title, date FROM entries";
$result = mysql_query($query);
				
while ( $result = mysql_fetch_assoc($result) ) {
				
	$id = $result["id"];
	$title = $result["title"];
	$date = $result["date"];
					
	echo "<div class=\"recent_entries\">";
	echo "<a href=\"archives.php?id=" . $id . "\">" . $title . "</a><br>";
	echo "<div class=\"date_line\">Posted on " . $date . "</div>";
	echo "</div>";
					
}

I have checked the database connection and it is working, the SQL statement is correct (tested in phpMyAdmin), and all of the field names from the associative array are correct.

There are two records in the database, and mysql_num_rows($result) returns both records.

The while() loop is returning only the first row, and I need it to return multiple rows...

Any help would be fantastic!!

Recommended Answers

All 3 Replies

Look at what you are doing in the following line:

while ( $result = mysql_fetch_assoc($result) )

You are using the $result variable for two different purposes, first it holds the query, then the results of the query. After the first loop iteration, you are passing the returned values back into the fetch function rather than passing in the query reference.

That has never been a problem before. However, changing the variable has helped. What would cause this to act differently this one time?

With the way that you are using it there, there isn't any way it would work properly. My only guess is that all the previous times you have used the variable that way, you were only retrieving one record.

Think about it in simple terms, you are essentially saying this:

$variable = 3;

while($variable == 3)
{
	$variable = 5;
}

There is no way for that loop to loop more than once, no matter how you look at it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.