2017-09-25 137 views
-3

嗨,我插入時出現問題data我的pdoquery只插入一個row爲什麼我的pdo查詢只插入最後一行

爲什麼最後行插入2倍,I,E friday pm

這裏是我做了什麼

請參閱我的構建query這裏http://phpio.net/s/54jc

<?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次?

請提前幫助我,謝謝!

+4

準備在循環之外,綁定並在循環中執行。 – Script47

+0

您的佔位符在哪些值中定義? – Script47

+0

我已經寫了這麼多的'代碼'到'一次執行查詢',但每次我必須執行下面的答案。請看這裏的演示http://phpio.net/s/5470 – EaB

回答

2

請插入$ stmt1-> 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();   
}