代码之家  ›  专栏  ›  技术社区  ›  TheOrdinaryGeek

为动态输入数组插入空值

  •  1
  • TheOrdinaryGeek  · 技术社区  · 6 年前

    使用PHP版本7.1.9、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 我的数据库中的值。这就是我的问题所在。

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

    • 默认值-空

    下面是我处理表单提交的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语法错误;检查与您的产品相对应的手册

    当我 var_dump(mac) 我得到;

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

    ' ' )在insert中,查询运行成功, 而不是 null empty 值被插入到数据库中。

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

    2 回复  |  直到 6 年前
        1
  •  1
  •   Nico Haase    6 年前

    我假设您使用错误的语法构建查询。使用给定的代码 INSERT

    INSERT INTO staff (mac) VALUES ()
    

    你的代码不能处理 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 ." )";
    }
    

    这有助于写出具体的 无效的

        2
  •  0
  •   Mangesh Sathe    6 年前
    $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')";
    

    ***使用内爆函数检查和形成