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
https://forums.phpfreaks.com/topic/23033-looping-through-mysql-result/
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]

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.