How to insert an actual NULL value into a nullable column?

前端 未结 5 1984
盖世英雄少女心
盖世英雄少女心 2020-12-20 15:26
function save($gmt, $name, $address, $phone, $remark)
{
    $query= \"INSERT INTO `user` (`gmt`, `name`, `address`, `phone`, `remark`) VALUES (\'$gmt\', \'$name\', \         


        
5条回答
  •  攒了一身酷
    2020-12-20 16:07

    This is PHP solution, but you have to use mysqli because mysql deprecated, please read more about mysqli. Also, you must consider SQL injection

    function save($gmt, $name, $address, $phone, $remark)
    {
      if(empty($phone)){
       $phone = 'NULL';
      }else{
       $phone = "'".$phone."'";
      }
      if(empty($remark)){
       $remark = 'NULL';
      }else{
       $remark = "'".$remark."'";
      }
        $query= "INSERT INTO `user` (`gmt`, `name`, `address`, `phone`, `remark`) VALUES ('$gmt', '$name', '$address', $phone, $remark)";
        mysql_query($query);
    }
    //tests
    save("a", "b", "c", "", "")."
    "; save("a", "b", "c", "d", "")."
    "; save("a", "b", "c", "d", "e")."
    "; /* INSERT INTO `user` (`gmt`, `name`, `address`, `phone`, `remark`) VALUES ('a', 'b', 'c', NULL, NULL) INSERT INTO `user` (`gmt`, `name`, `address`, `phone`, `remark`) VALUES ('a', 'b', 'c', 'd', NULL) INSERT INTO `user` (`gmt`, `name`, `address`, `phone`, `remark`) VALUES ('a', 'b', 'c', 'd', 'e') */ ?>

    DEMO

提交回复
热议问题