Jump to content

PHP PDO object null check


ashutoash

Recommended Posts

@cunoodle2: Here is what I am doing. Its a simple query:

 

$result_download = $db->query("SELECT download_hits as total_hits from date1_dcerpc where time = 1314712800 ");

 

I know there are no download_hits at 1314712800 as there is no entry for 1314712800 in the table so the return should be null. I want to know how to check if the PDO object returns null.

Technically your query will NOT return NULL.  It will return zero results.

 

From the Manual: Counting rows returned by a SELECT statement

 

For most databases, PDOStatement::rowCount() does not return the number of rows affected by a SELECT statement. Instead, use PDO::query() to issue a SELECT COUNT(*) statement with the same predicates as your intended SELECT statement, then use PDOStatement::fetchColumn() to retrieve the number of rows that will be returned. Your application can then perform the correct action.

 

 

<?php
$sql = "SELECT download_hits as total_hits from date1_dcerpc where time = 1314712800";
if ($res = $conn->query($sql)) {

    /* Check the number of rows that match the SELECT statement */
  if ($res->fetchColumn() > 0) {

        /* Issue the real SELECT statement and work with the results */
         $sql = "SELECT download_hits as total_hits from date1_dcerpc where time = 1314712800";
       foreach ($conn->query($sql) as $row) {
           print "Name: " .  $row['download_hits'] . "\n";
         }
    }
    /* No rows matched -- do something else */
  else {
      print "No rows matched the query.";
    }
}

$res = null;
$conn = null;
?>

 

Thanks cunoodle2 and Jet4Fire. The errorcode thing did not work but I am doing a count of rows and if count == 0, I am displaying ND.  :).

This is solved. But most of my PDO statments, if there is no data, give out a warning PHP Warning:  Invalid argument supplied for foreach(). I read somewhere that @ can be used to suppress these but that doesn't work. How can I suppress these? Those warnings are filling up my logs like anything.

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.