Insert NULL instead of empty values using MySQLi

五迷三道 提交于 2020-01-14 15:55:55

问题


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

回答1:


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.




回答2:


Since PHP 7 you can set the default value for a variable using the 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.

As a side note you should read How to get the error message in MySQLi? instead of print out the error messages manually.



来源:https://stackoverflow.com/questions/16586255/insert-null-instead-of-empty-values-using-mysqli

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