使用MySQLi插入NULL而不是空值 [英] Insert NULL instead of empty values using MySQLi

查看:91
本文介绍了使用MySQLi插入NULL而不是空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有一些可选字段的表格.在数据库中,这些字段设置为接受NULL. 如果某些字段为空,则下面的代码将引发错误.您能协助避免这种情况的最佳方法是什么?我唯一想到的解决方案是将vars设置为''(如果为empty()).

I have a form with some optional fields. In the database those fields are set to accept NULL. The code below will throw an error if some field is empty. Could you please assist on what is the best way to avoid this? The only solution I was thinking of is to set the vars to ' ' if is empty().

$query = "INSERT INTO gifts (dateRequest, firstName, lastName, note, lastUpdated) 
    VALUES (?, ?, ?, ?, NOW())";
if ($stmt = $dbc->prepare($query)) {
    $dateRequest = $_POST['dateRequest'];
    $firstName = $_POST['firstName'];
    $lastName = $_POST['lastName'];
    $note = $_POST['note'];
    $stmt->bind_param('ssss', $dateRequest, $firstName, $lastName, $note);
    if ($stmt->execute()) {
        $stmt->close();
        header('Location: index.php');
    } else {
        echo $stmt->error;
    }
}

推荐答案

我宁愿建议在定义它们之前先检查$_POST参数,以便如果变量不为空则设置values,否则设置为NULL

I would rather suggest to check $_POST paramenters before definied them so if a variable is not empty set values otherwise set as NULL

if(!empty($_POST['dateRequest'])) { $dateRequest = $_POST['dateRequest']; } else { $dateRequest = NULL; }
if(!empty($_POST['firstName'])) { $firstName = $_POST['firstName']; } else { $firstName  = NULL; }
if(!empty($_POST['lastName'])) { $lastName = $_POST['lastName']; } else { $lastName = NULL; }
if(!empty($_POST['lastName'])) { $note = $_POST['note']; } else { $note = NULL; }

这将防止您在查询中传递空参数.

This will prevent you to pass empty parameters in your query.

这篇关于使用MySQLi插入NULL而不是空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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