PHP SQL Null

The result produced by SQL SELECT command may contain NULL or non-Null values. So when we need to work on these values then the NULL values may not work properly.

PHP SQL Null

PHP SQL Null

     

This example describes about handling NULL values in sql query in php.

The result produced by SQL SELECT command may contain NULL or non-Null values. So when we need to work on these values then the NULL values may not work properly.

MySQL provides some operators to handle the problem.

  • IS NULL: This operator returns true if column value is NULL.

  • IS NOT NULL: This operator returns true if column value is not NULL.

Table: tutorial

Source Code of sql_null.php 

<?php
  $dbhost = "localhost";
  $dbuser = "root";
  $dbpass = "root";
  $conn = mysql_connect($dbhost, $dbuser, $dbpass);
  if(! $conn ){
  die("Could not connect: " . mysql_error());
  }
  
  if(isset($t_count)){
  $sql = 'SELECT t_author, t_count FROM  tutorial WHERE t_count IS NULL';
  } else {
  $sql = 'SELECT t_author, t_count FROM  tutorial WHERE t_count IS NOT NULL';
  }

  mysql_select_db("test");  
  $result = mysql_query( $sql, $conn );
  if(! $result ){
  die("Could not get data: " . mysql_error());
  }
  while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
  echo "Author: ".$row['t_author']."<br>". "Count: ".$row['t_count']."<br>". "<br>";
  }
  echo "Fetched data successfully\n";
  mysql_close($conn);
?>

Download Source Code

Output: