Jump to content

[SOLVED] How to check empty result from database query


williamZanelli

Recommended Posts

I was just wondering how I could check an empty result from the database.

 

Say I run the following query and it returns nothing

 

$sql = "Select * from links where user_id = 'Addidas'"
$records = mysql_fetch_array($sql)

 

I've seen people write

 

if ($records){
// do something with the result
}
else{
echo "No items";
}

 

what exactly does if ($records) mean? I'm from a java background, where you would be required to write something like, if(result != nul){...

 

Thanks for your thoughs

 

William

 

PS: Does anyone know of a good, comprehensive tutorial on PHP, outlining the basics, such as above, arrays etc. thanks.

 

Your example is a little floored, but basically, you need to check returned values from function calls to make sure they contain what you expect.

 

A better example.

 

<?php

  $sql = "SELECT foo FROM bar";
  $result = mysql_query($sql);

  // check your call to mysql_query succeeded.
  if ($result) {
    // check $result holds data
    if (mysql_num_rows($result)) {
      // in here it is safe to use $result to display data
      while ($row = mysql_fetch_assoc($result) {
        echo $row['foo'] . "<br />";
      }
    } else {
      // no data found.
    }
  } else {
    // query failed, handle error.
  }

?>

 

Theres a good link in my signiture if your just getting started.

<?php

  $sql = "SELECT foo FROM bar";
  $result = mysql_query($sql);

  // check your call to mysql_query succeeded.
  if ($result) {
    // check $result holds data
    if (mysql_num_rows($result)) {
      // in here it is safe to use $result to display data
      while ($row = mysql_fetch_assoc($result) {
        echo $row['foo'] . "<br />";
      }
    } else {
      // no data found.
    }
  } else {
    // query failed, handle error.
  }

?>

 

$sql = "Select * from links where user_id = 'Addidas'";
$records = mysql_query($sql);
$records_count = mysql_num_rows($records);

if($records_count > 0){
  //do functions
}else{
  //parse error
}

 

For this you can check if there is a specific number of returns for instance if($records_count === 1){ and so on

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.