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

WBOY
Release: 2023-09-07 18:18:02
forward
922 people have browsed it

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)
Copy after login

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);
?>
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!