Jump to content


Photo

Looping through MySQL result


  • Please log in to reply
2 replies to this topic

#1 Kelset

Kelset
  • Members
  • PipPip
  • Member
  • 29 posts

Posted 04 October 2006 - 11:33 PM

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

#2 trq

trq
  • Staff Alumni
  • Advanced Member
  • 31,041 posts

Posted 04 October 2006 - 11:38 PM

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

<?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();
  }
?>


#3 Kelset

Kelset
  • Members
  • PipPip
  • Member
  • 29 posts

Posted 04 October 2006 - 11:51 PM

Thanks for the help that should do the trick.

Cheers!
Stephen




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users