Hi all. I am having a problem I've not encountered before. When using mysql_fetch_assoc() in while(), I am getting the following error:

Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in archives.php on line 81

However, when taking it out of the while(), it works fine. The following is the code snippet...

$query = "SELECT * FROM comments WHERE archive_id = '$archive_id'";
$result = mysql_query($query);

while ( $result = mysql_fetch_assoc($result) ) {

   $date = $result["date"];
   $name = $result["name"];
   $comments = $result["comments"];

   echo "$date, $name, $comments";

}

I have checked database connections, I've run the query through phpMyAdmin, and checked for spelling/syntax errors.

Any ideas? Thanks!

Recommended Answers

All 3 Replies

Try this:

$query = "SELECT * FROM comments WHERE archive_id = '$archive_id'"; 
echo $query;
exit();
$res = mysql_query($query); 
while ( $result = mysql_fetch_assoc($res) ) { 
$date = $result["date"]; 
$name = $result["name"]; 
$comments = $result["comments"]; 
echo "$date, $name, $comments"; 
}

I had to remove the exit(), but it worked fantastically. Why would changing $result to $res work differently than keeping $result? I'm calling result earlier in the page, however, it's never caused me problems before...

It will work in a single line statement, but not iteratively. This is because the very first time you issue the statement, you have swapped $result--the full result set for $result--the single row array. The next time through the loop, $result is the array--not the result set.

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.