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

前端 未结 5 1997
盖世英雄少女心
盖世英雄少女心 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:26

    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

提交回复
热议问题