Jump to content

(MYSQL) Multiple conditions in while statement


arakash

Recommended Posts

Hello everyone! I'm new here on phpfreaks :P - Here's my problem. I get "1 <br/> 2" echoed, but not the query results. the connect() function connects and selects a table in a mysql database.

 

Here's the code:

<?php
				connect();

				$query = "SELECT `title`, `body`, `date` FROM `tutorials` ORDER BY `date` DESC" or die ("Query Error");

				$counter = 0;

				if ($query_run = mysql_query($query)) {

					while ($query_row = mysql_fetch_assoc($query_run)) && ($counter <= 2) {
						$title = $query_row['title'];
						$body = $query_row['body'];
						$date = $query_row['date'];
						$counter ++;
						echo $counter;
						echo "<br/>";
						echo $title;
						echo $body;
						echo $date;
					}
				}
			?>

 

If anyone has any idea, please help! - I'm been battling this for a few hours now :P

Your while has a syntax error.  Should be:

 

while($query_row = mysql_fetch_assoc($query_run) && $counter <= 2)

 

Also, as an aside, you don't need to assign your columns to a variable only to echo them.  There's nothing wrong with simply writing:

 

echo $query_row['title'];

Also, as an aside, you don't need to assign your columns to a variable only to echo them.  There's nothing wrong with simply writing:

echo $query_row['title'];

 

Hello! Thanks for your quick reply.

Hmm.. I think I put them in variables for a reason.. wait, I need to check. I don't remember. haha :P

while($query_row = mysql_fetch_assoc($query_run) && $counter <= 2)

 

That does not do what your expecting.  $query_row is going to be assigned the results of the && operation, not the return value of mysql_fetch_assoc().  So $query_row is going to be either bool(true) or bool(false), not an array with the row content.

 

To fix it, put parenthesis around the assignment:

 

while(($query_row = mysql_fetch_assoc($query_run)) && $counter <= 2)

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.