Home >Backend Development >PHP Tutorial >How can we handle NULL values ​​stored in MySQL table using PHP script?

How can we handle NULL values ​​stored in MySQL table using PHP script?

WBOY
WBOYforward
2023-09-07 18:17:06992browse

How can we handle NULL values ​​stored in MySQL table using PHP script?

We can use if...else conditions in PHP scripts to prepare queries based on NULL values. To illustrate this, we use the following example -

Example

In this example, we use a table named 'tcount_tbl' which contains the following data -

mysql> SELECT * from tcount_tbl;
+-----------------+----------------+
| tutorial_author | tutorial_count |
+-----------------+----------------+
|      mahran     |       20       |
|      mahnaz     |      NULL      |
|       Jen       |      NULL      |
|      Gill       |       20       |
+-----------------+----------------+
4 rows in set (0.00 sec)

Now, below is a PHP script that gets the value of 'tutorial_count' from outside and compares it with the value available in the field.

<?php
   $dbhost = &#39;localhost:3036&#39;;
   $dbuser = &#39;root&#39;;
   $dbpass = &#39;rootpassword&#39;;
   $conn = mysql_connect($dbhost, $dbuser, $dbpass);

   if(! $conn ) {
      die(&#39;Could not connect: &#39; . mysql_error());
   }

   if( isset($tutorial_count )) {
      $sql = &#39;SELECT tutorial_author, tutorial_count FROM tcount_tbl
         WHERE tutorial_count = $tutorial_count&#39;;
   } else {
      $sql = &#39;SELECT tutorial_author, tutorial_count FROM tcount_tbl
         WHERE tutorial_count IS $tutorial_count&#39;;
   }

   mysql_select_db(&#39;TUTORIALS&#39;);
   $retval = mysql_query( $sql, $conn );

   if(! $retval ) {
      die(&#39;Could not get data: &#39; . mysql_error());
   }

   while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
      echo "Author:{$row[&#39;tutorial_author&#39;]} <br> ".
         "Count: {$row[&#39;tutorial_count&#39;]} <br> ".
         "--------------------------------<br>";
   }
   echo "Fetched data successfully</p><p>";
   mysql_close($conn);
?>

The above is the detailed content of How can we handle NULL values ​​stored in MySQL table using PHP script?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete

Related articles

See more