2013-05-16 131 views
3

我有一些不需要的字段。在數據庫中,這些字段被設置爲Null:YES。 如果某個字段爲空,則下面的代碼將引發錯誤。請你幫助避免這種情況的最佳等待時間,我唯一想到的解決方案是將變量設置爲「'如果爲空()」。Mysqli插入語句 - 空值

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

回答

2

我寧願建議檢查$_POST paramenters definied他們之前,所以如果一個變量是不是空集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; } 

這會防止你通過在查詢空參數。