我有一个带有一些可选字段的表单。在数据库中,这些字段设置为接受 NULL。如果某些字段为空,下面的代码将引发错误。您能否协助解决避免这种情况的最佳方法?我想到的唯一解决方案是将变量设置为''如果为空()。
$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;
}
}