如果不为空,则将值插入数据库,如果为空,则将值设置为“null”

时间:2015-11-13 03:06:13

标签: php mysql database if-statement

我是mysql的新手。所以我的问题是如果主题字段不为空,我想将数据库中的$ status设置为'IN PROCESS'。如果主题为空,状态将设置为空。这是我的代码,当我运行它时,状态没有任何变化。谢谢!

<?php
    if(isset($_POST['submit']))
     {
         $dbhost = 'localhost';
         $dbuser = 'root';
         $dbpass = '';
         $conn = mysql_connect($dbhost, $dbuser, $dbpass);

         mysql_select_db('course');

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

         $code= $_POST['code'];
         $subject= $_POST['subject'];
         $status= $_POST['status'];

         $sql = "INSERT INTO form(code,subject,status)
         VALUES('$code','$subject','$status')";

         $retval = mysql_query( $sql, $conn );

         if(!empty($_POST['subject'])) {
                $status = 'IN PROCESS';
            }      
            else $status = 'null';

         if(! $retval )
         {
         die('Could not enter data: ' . mysql_error());
         }

         else
         {
             ?>
             <div class="alert alert-success">
               <strong>Success!</strong> .
             </div>
             <?php
         }


         mysql_close($conn);
      }
 ?>

2 个答案:

答案 0 :(得分:0)

尝试在 if condition 之后添加Insert语句。因为$status的值已经在条件之前插入。

<?php
        if(isset($_POST['submit']))
         {
             $dbhost = 'localhost';
             $dbuser = 'root';
             $dbpass = '';
             $conn = mysql_connect($dbhost, $dbuser, $dbpass);

             mysql_select_db('course');

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

             $code= $_POST['code'];
             $subject= $_POST['subject'];
             $status= $_POST['status'];

             if(!empty($_POST['subject'])) {
                    $status = 'IN PROCESS';
                }      
                else $status = 'null'; 
             //put it here
             $sql = "INSERT INTO form(code,subject,status)
             VALUES('$code','$subject','$status')";

             $retval = mysql_query( $sql, $conn );

             if(! $retval )
             {
             die('Could not enter data: ' . mysql_error());
             }

             else
             {
                 ?>
                 <div class="alert alert-success">
                   <strong>Success!</strong> .
                 </div>
                 <?php
             }


             mysql_close($conn);
          }
     ?>

答案 1 :(得分:-1)

设置

if(!empty($_POST['subject'])) {
    $status = 'IN PROCESS';
}      
else $status = 'null';
在查询之前

$sql = "INSERT INTO form(code,subject,status)
     VALUES('$code','$subject','$status')";