简体   繁体   English

使用MySQLi插入NULL而不是空值

[英]Insert NULL instead of empty values using MySQLi

I have a form with some optional fields. 我有一个带有一些可选字段的表单。 In the database those fields are set to accept NULL. 在数据库中,这些字段设置为接受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;
    }
}

I would rather suggest to check $_POST paramenters before definied them so if a variable is not empty set values otherwise set as NULL 我宁愿建议在定义它们之前检查$_POST参数,这样如果变量不为空则设置values否则设置为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. 这将阻止您在查询中传递空参数。

Since PHP 7 you can set the default value for a variable using the elvis-operator. 从PHP 7开始,您可以使用elvis-operator设置变量的默认值。

$dateRequest = $_POST['dateRequest'] ?: null;
$firstName = $_POST['firstName'] ?: null;
$lastName = $_POST['lastName'] ?: null;
$note = $_POST['note'] ?: null;

If any of the fields is empty or undefined it will set the value to NULL and insert that into database instead. 如果任何字段为空或未定义,则将该值设置为NULL并将其插入到数据库中。

As a side note you should read How to get the error message in MySQLi? 作为旁注,您应该阅读如何在MySQLi中获取错误消息? instead of print out the error messages manually. 而不是手动打印出错误消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM