我已切换到 PDO,但在构建和执行 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();
}
关于php - 使用 PDO 通过单个查询插入多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19627423/