Jump to content

Looping through MySQL result


Kelset

Recommended Posts

Hey all!

Well this might sound really simple but I have not been able to firgure it out and thought I would ask you find folks.
What I'm doing is querying a MySQL database and getting results then looping through the results.

//Sample of my code
$query = "SELECT * FROM there";
$result = mysql_query($query);


Ok here is where I don't understand, I use the while loop to loop through the results which looks like this

//Sample of my code
while ($row = mysql_fetch_array($result)) {


Now I want to check and see if anything is in results I tried

//Sample of my code
if (!$results) {
}

but this does not seem to work for me, I'm assuming something always gets passed back even if null.
So I tried something like the follow code

//Sample of my code
$row = mysql_fetch_array($query);

if (!$row) {
    //Display message
}else{
    while ($row = mysql_fetch_array($result)); {
}


Now I know I'm over writing the var $row but I thought this would not matter, even if it was bad coding.
This works but the first record does not display when I do it this way.

So do I have to use a for() loop? get the number of rows and loop with for(). Just thought I would ask
and see what people thought or how maybe some of you loop through your results.

Cheers!
Stephen
Link to comment
Share on other sites

You want to check your result before the loop. eg;

[code=php:0]
<?php
  // connect to db.
  $sql = "SELECT * FROM db";
  $result = mysql_query($sql);
  if ($result) {
    if (mysql_num_rows($result)) {
      while ($row = mysql_fetch_assoc($result)) {
        // display.
      }
    } else {
      echo "no results found";
    }
  } else {
    echo "query failed ".mysql_error();
  }
?>
[/code]
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

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.

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