duanci6484 2013-05-16 11:29
浏览 137
已采纳

使用MySQLi插入NULL而不是空值

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;
    }
}
  • 写回答

2条回答 默认 最新

  • dsue14118 2013-05-16 11:44
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64
  • ¥15 iOS 自定义输入法-第三方输入法