我在插入data
pdo
query
时遇到问题,只插入一个row
。
为什么最后一行插入2次,i,e friday pm
这就是我所做的
看到我构建的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次?
请提前帮助我!!!!
答案 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();
}