如何在可为空的列中插入实际的NULL值? [英] How to insert an actual NULL value into a nullable column?

查看:161
本文介绍了如何在可为空的列中插入实际的NULL值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

function save($gmt, $name, $address, $phone, $remark)
{
    $query= "INSERT INTO `user` (`gmt`, `name`, `address`, `phone`, `remark`) VALUES ('$gmt', '$name', '$address', '$phone', '$remark')";
    mysql_query($query);
}

此处,地址,电话和备注可以为NULL.每当变量设置为NULL并且列为空时,我都需要保存NULL,而不是插入空字符串.

Here, address, phone, and remark can be NULL. I need it to save NULL whenever the variable is set to NULL and the column is nullable, instead of inserting an empty string.

如何使用PHP将NULL值插入数据库?

How can I insert NULL value into the database using PHP?

推荐答案

这是PHP解决方案,但是由于不建议使用mysql,因此必须使用mysqli,请阅读有关 SQL注入

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", "", "")."<br>";
save("a", "b", "c", "d", "")."<br>";
save("a", "b", "c", "d", "e")."<br>";
/*
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')
*/
?>

演示

这篇关于如何在可为空的列中插入实际的NULL值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆