Best practice to insert NULL to MySQL using PHP

旧街凉风 提交于 2019-12-18 07:43:09

问题


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);
}

Here address, phone and remark can be NULL value. I need it so that when I pass a null parameter into my function it stores an empty value in the database (NULL). I need to know what the best solution for doing this is.

Thanks.


回答1:


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




回答2:


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




回答3:


PHP doesn't print NULL - it is just an empty string. So in your example you will try to insert '', which in SQL again is an empty string.

You have to use NULL (without quotes).

And the best practice to achieve that is to use an ORM or a PHP framework with a database abstraction layer which does this for you.




回答4:


Using ternary operator, you can also use this

$add = ($address == '' ? NULL : $address);
$phn = ($phone == '' ? NULL : $phone);
$rmk = ($remark == '' ? NULL : $remark);


来源:https://stackoverflow.com/questions/14600650/best-practice-to-insert-null-to-mysql-using-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!