【问题标题】:Inserting Null Values for Dynamic Inputs Array为动态输入数组插入空值
【发布时间】:2019-03-15 06:27:33
【问题描述】:

使用 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]:语法错误或访问冲突:1064 你有一个 SQL 语法错误;检查与您对应的手册 正确语法的 MySQL 服务器版本.. ..

当我var_dump(mac) 我得到;

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

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

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

感谢任何建议。

【问题讨论】:

  • 你能分享完整的生成查询吗?
  • 我认为你必须从字面上插入NULL,如果值为空:$sql = "INSERT INTO staff (mac) VALUES (" . ($arr_mac[$i] ? "'{$arr_mac[$i]}'" : 'NULL') . ")

标签: php html mysql arrays mariadb


【解决方案1】:

我假设您使用错误的语法构建查询。使用给定的代码,您的 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

【讨论】:

    【解决方案2】:
    $arr_mac = $_POST['mac'] ;
    $batchInsert = array();
    for ($i = 0; $i < count($arr_mac); $i++) {
        if( "" == trim($arr_mac[$i])) {
            $arr_mac[$i] = 'NULL';
        }
           $batchInsert = array_push($arr_mac[$i]);
    }
    $insertValues = implode("','", $batchInsert)
    $sql = "INSERT INTO staff (mac) VALUES ('$batchInsert')";
    

    ***check ' 和 , 使用 implode 函数形成

    这将插入 N 号。单个 INSERT 语句中的值,将执行得更快!

    【讨论】:

    • 你确定吗?这如何将请求的NULL 值添加到数据库中?
    • 感谢@NicoHaase 突出显示,我从记事本中粘贴了错误的片段!
    猜你喜欢
    • 2015-02-12
    • 1970-01-01
    • 1970-01-01
    • 2019-01-24
    • 2019-05-30
    • 1970-01-01
    • 1970-01-01
    • 2016-05-25
    • 1970-01-01
    相关资源
    最近更新 更多