【问题标题】:Arrayed input value inserts empty record in mysql数组输入值在mysql中插入空记录
【发布时间】:2015-02-12 22:01:02
【问题描述】:

我使用了 4 个同名输入框。我一次只填充一个输入框并使用 php 插入数据库。但是执行以下方法会插入三个空记录以及填充值的第 4 条记录。需要帮助!

HTML

                <input type="text" name="abc[]" id="abc" value=""> 
                <input type="text" name="abc[]" id="abc"  value="">
                <input type="text" name="abc[]" id="abc"  value="">
                <input type="text" name="abc[]" id="abc" value="">

php

$abc = $_POST['abc'];
        if (is_array($abc)) {
                foreach($abc as $c) {

$insert="INSERT INTO item(productid) VALUES ('$c')";
                    $insert2=mysql_query($insert);              }

}

【问题讨论】:

    标签: php html mysql arrays


    【解决方案1】:

    以下代码生成 1 个 INSERT 语句。如果您建议您只使用输入中的 1 个值,并且可以强制执行此操作,您可以省略 $value = rtrim($value, ",");,这会删除尾随的 ,。

    我还建议您使用 mysqli 或 PDO,因为不推荐使用 mysql_functions。

     $value = "";
    if(isset($_POST['submit'])){
        if(isset($_POST['abc'])){
            foreach($_POST['abc'] as $c) {
            if(!empty($c)){
            $value .= "'".$c."',";}
            }
            $value = rtrim($value, ",");
        }
        $insert="INSERT INTO item(productid) VALUES ($value)";
        echo $insert;//Remove after testing
    }   
    

    【讨论】:

      【解决方案2】:

      只需检查该值是否不为空,然后插入数据库。

      $abc = $_POST['abc'];
      if (is_array($abc)) {
          foreach ($abc as $c) {
              if(!empty($c)){
                  $insert = "INSERT INTO item(productid) VALUES ('$c')";
                  $insert2 = mysql_query($insert);
              }
          }
      
      }
      

      【讨论】:

        猜你喜欢
        • 2019-07-06
        • 1970-01-01
        • 2019-03-15
        • 1970-01-01
        • 2014-06-17
        • 2017-11-16
        • 2012-07-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多