[英]Inserting multiple rows with a single query using PDO
我已切換到PDO,並且在構建和執行SQL查詢時遇到麻煩,該SQL查詢將僅執行一次即可插入多行。
json_decode之后的$data
內容:
Array (
[action] => load
[app] => CA
[street_type] => AVE
[place_type] => --
[state] => AL
)
碼:
$data = json_decode(file_get_contents("php://input"));
$query = "REPLACE INTO tblsettings(setApp, setIP, setKey, setValue)VALUES";
$qPart = array_fill(0, count($data), "(?, ?, ?, ?)");
$query .= implode(",", $qPart);
$stmt = $db->prepare($query);
foreach($data as $key => $val){
$query = "REPLACE INTO tblsettings(setApp, setIP, setKey, setValue)VALUES";
$qPart = array_fill(0, count($data), "(?, ?, ?, ?)");
$query .= implode(",", $qPart);
$stmt = $db->prepare($query);
$i = 1;
if(!is_array($val)){
$stmt->bindParam($i++, $data->app);
$stmt->bindParam($i++, gethostbyname(trim(gethostname())));
$stmt->bindParam($i++, $key);
$stmt->bindParam($i++, $val);
}
if ($stmt->execute()){
echo "Success";
}else{
echo $stmt->errorCode();
}
}
我猜$i = 1;
應該在for
循環內,在if
循環外,因為對於每個for循環,它將增加4,這是我們不希望的,我們希望從1開始並達到4,然后為每個for
循環退出
$data = json_decode(file_get_contents("php://input"), true);
$query = "REPLACE INTO tblsettings(setApp, setIP, setKey, setValue)VALUES";
$qPart = array_fill(0, count($data), "(?, ?, ?, ?)");
$query .= implode(",", $qPart);
$stmt = $db->prepare($query);
foreach($data as $key => $val){
$i = 1; //for every for loop reset it to 1
if(!is_array($val)) {
$stmt->bindParam($i++, $data->app); //here it will be 1
$stmt->bindParam($i++, gethostbyname(trim(gethostname()))); //here it will be 2
$stmt->bindParam($i++, $key); //here it will be 3
$stmt->bindParam($i++, $val); //here it will be 4
}
}
if ($stmt->execute()){
echo "Success";
}else{
echo $stmt->errorCode();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.