php - 为动态输入数组插入空值

标签 php html mysql arrays mariadb

使用 PHP 版本 7.1.9,MariaDB 10.1.26。

我正在向 MySQL 数据库提交一组表单数据。该表单允许添加动态输入,当添加动态输入时,它们看起来像这样;

// I have removed additional html form code for brevity
<input type="text" name="mac[]">
<input type="text" name="mac[]">
<input type="text" name="mac[]">
etc...

有时这些输入会是空的,这是允许的。当输入为空时,我想将一个 NULL 值插入到我的数据库中。这是我遇到问题的地方。

我已确保我的数据库表设置为;

  • 允许 null = 是
  • 默认 - 空

我处理表单提交的 PHP 代码如下(请忽略任何安全漏洞,这是简化的代码)

// I have removed additional php code for brevity
$arr_mac = $_POST['mac'] ? "'".$_POST['mac']."'" : 'NULL';
for ($i = 0; $i < count($arr_mac); $i++) {
    $sql = "INSERT INTO staff (mac) VALUES ( ".$arr_mac[$i]." )
}

我收到的错误是;

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax.. ..

当我 var_dump(mac) 我得到;

[mac] => Array
  (
    [0] =>
    [1] => 
    [2] =>  
  )

如果我在插入中将 PHP 更改为以下内容(注意附加的 ' '),查询将成功运行, 而不是 null 值, 值被插入到数据库中。

$arr_mac = $_POST['mac'] ;
for ($i = 0; $i < count($arr_mac); $i++) {
    $sql = "INSERT INTO staff (mac) VALUES (' ".$arr_mac[$i]." ')
}

如有任何建议,我们将不胜感激。

最佳答案

我假设您使用错误的语法构建查询。使用给定的代码,您的 INSERT 可能如下所示:

INSERT INTO staff (mac) VALUES ()

您的代码未正确处理 NULL 情况 - 将变量设置为 NULL 不会导致使用文字 NULL 进行构建查询。

这可能有帮助:

$arr_mac = $_POST['mac'] ? "'".$_POST['mac']."'" : 'NULL';
for ($i = 0; $i < count($arr_mac); $i++) {
    $value = $arr_mac[$i];
    if(!$value) {
        $value = 'NULL';
    } else {
        $value = your_favorite_escaping_algorithm($value);
    }
    $sql = "INSERT INTO staff (mac) VALUES ( ". $value ." )";
}

这有助于写出语法正确查询所需的特定 NULL

关于php - 为动态输入数组插入空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52738597/

相关文章:

php - 在 MySQL ENUM 值中使用撇号将填充 HTML 组合框以进行数据库搜索

php - Mysql 连接在 docker 中被拒绝

javascript - 编辑器 : Remove selection and set cursor position at the end of selection

php - 将 json 响应中的嵌套数组插入 mysql

php - wpdb->prepare() 返回 NULL

php - 如何获取MySQL数据库中的总行数?

javascript - 如何将模态框向下移动

html - 如果链接是图像,则从 a-Tag 中删除边框

Mysql 表允许相同的列名两次并在表中显示两列

mysql - 我真的需要关闭 MySql 服务器来设置全局变量 log_bin_trust_function_creators 吗?