Jump to content

(MYSQL) Multiple conditions in while statement


arakash
 Share

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

Link to comment
Share on other sites

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'];

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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)

 

 

Link to comment
Share on other sites

This thread is more than a year old.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • 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.