How to insert an actual NULL value into a nullable column?
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')
*/
?>
DEMO
Try switching to prepared statements (which as a bonus is less prone to SQL injections).
function save($gmt, $name, $address, $phone, $remark)
{
if(!isset($phone) || empty($phone)) { $phone = null; }
if(!isset($remark) || empty($remark) { $remark = null; }
$db = new PDO(...);
$stmt = $db->prepare("INSERT INTO `user` (`gmt`, `name`, `address`, `phone`, `remark`) VALUES (:gmt, :name, :address, :phone, :remark)");
$stmt->bindValue("gmt", $gmt, PDO::PARAM_STR);
$stmt->bindValue("name", $name, PDO::PARAM_STR);
$stmt->bindValue("address", $address, PDO::PARAM_STR);
$stmt->bindValue("phone", $phone, PDO::PARAM_STR);
$stmt->bindValue("remark", $remark, PDO::PARAM_STR);
$stmt->execute();
}
This will handle the null
values correctly in MySQL