多行插入中的重复行

时间:2011-03-15 20:16:18

标签: php insert multidimensional-array pdo

我正在尝试使用PDO将多行插入到我的数据库中。我正在使用     if count(array_filter($ value)> 0)以防止插入空行。下面的代码导致最后一行插入两次。

任何想法为什么? 感谢...

<td><input type="text" name="row[0][posnum]" value="123456"></td>  
         <td><input type="text" name="row[0][comment]" value="nancy"></td>  
         <td><input type="text" name="row[0][eff_dt]" value="12/12/2010"></td>  
        </tr>  
<tr>  
         <td><input type="text" name="row[1][posnum]" value="987654"></td>  
         <td><input type="text" name="row[1][comment]" value="bob"></td>  
         <td><input type="text" name="row[1][eff_dt]" value="01/01/2011"></td>  
         </tr>  
<tr>  
         <td><input type="text" name="row[2][posnum]"></td>  
         <td><input type="text" name="row[2][comment]"></td>  
         <td><input type="text" name="row[2][eff_dt]"></td>  
         </tr>

PDO插入代码

$arr = $_POST["row"];   
       # connect to the database  
    try {  
      $DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);  
      $DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );  

  //code in question      
   foreach($arr as $key=>$value){

            # the data we want to insert  

        if(count(array_filter($value)) >0){

           $data = array( 'submitby' => $_POST['submitby'], 'posnum' => $value['posnum'], 'comment' => $value['comment'], 'eff_dt' => date("Y-m-d",
           strtotime($value['eff_dt'])) );  

       }

  $STH = $DBH->prepare("INSERT INTO table (submitby, POS_NUM, COMMENT,EFF_DT) value (:submitby, :posnum, :comment, :eff_dt)");  
            $STH->execute($data);  


           }

}  //end try  
    catch(PDOException $e) {  
        echo "I'm sorry, Dave. I'm afraid I can't do that.";  
        echo $e->getMessage();  
    }  

}

1 个答案:

答案 0 :(得分:0)

你的意思不是,也许是逻辑......

$arr = $_POST["row"];
# connect to the database
try {
    $DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
    $DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

    //code in question
    foreach($arr as $key=>$value){
        # the data we want to insert  

        if(count(array_filter($value)) >0){

           $data = array( 'submitby' => $_POST['submitby'], 'posnum' => $value['posnum'], 'comment' => $value['comment'], 'eff_dt' => date("Y-m-d",
           strtotime($value['eff_dt'])) );  

           $STH = $DBH->prepare("INSERT INTO table (submitby, POS_NUM, COMMENT,EFF_DT) value (:submitby, :posnum, :comment, :eff_dt)");
           $STH->execute($data); 
        }
    }
} //end try
   catch(PDOException $e) {
   echo "I'm sorry, Dave. I'm afraid I can't do that.";
   echo $e->getMessage();
}