为什么我的pdo查询只插入最后一行

时间:2017-09-25 09:08:44

标签: php mysql pdo

我在插入data pdo query时遇到问题,只插入一个row

为什么最后一行插入2次,i,e friday pm

这就是我所做的

请在http://phpio.net/s/54jc

看到我构建的query
<?php   

function returnValuesNoOfTimes($count,$fields = array()){

    $str = str_repeat("(:{$fields['user_id']},:{$fields['day']},:{$fields['am_pm']}),",$count); 

   return rtrim($str,", ");        
}


function queryBuilderLocallyDone($data = array(),$fields = array(),$user_id,$object_count){


 /*Inserting user values*/  

$valuesTimes = returnValuesNoOfTimes($object_count,$fields);


  $db = getDB();   


  $sql1="INSERT INTO availability({$fields['user_id']},{$fields['day']},{$fields['am_pm']}) VALUES {$valuesTimes}";  



  $stmt1 = $db->prepare($sql1);               



    foreach($data as $avb){         

      $stmt1->bindParam("user_id", $user_id,PDO::PARAM_STR);
      $stmt1->bindParam("day",$avb['day'],PDO::PARAM_STR);  
      $stmt1->bindParam("am_pm",$avb['time'],PDO::PARAM_STR);                                           
    }   



   $stmt1->execute();        



     // $stmt1->execute();                 


}   

我的起点是functions

以上
   $data = [
      0 => ['day'=> 'monday','time'=>'am'],
      1 => ['day'=> 'friday','time'=>'pm']
    ];

    $user_id = 2;


    $total = count($data);

     $fields = ['id'=>'','user_id'=>'user_id','day'=>'day','am_pm'=>'am_pm'];   
     queryBuilderLocallyDone($data,$fields,$user_id,$total);

问题:为什么最后一行插入2次?

请提前帮助我!!!!

1 个答案:

答案 0 :(得分:3)

请插入$ stmt1-&gt; execute();在foreach

foreach($data as $avb){         

  $stmt1->bindParam("user_id", $user_id,PDO::PARAM_STR);
  $stmt1->bindParam("day",$avb['day'],PDO::PARAM_STR);  
  $stmt1->bindParam("am_pm",$avb['time'],PDO::PARAM_STR);                                           
  $stmt1->execute();        
}