PHP高效更新数据库记录

31. October 2016 DataBase 0

大批量插入或更新数据库记录,使用循环费时费力,数据库压力会更大,插入可以在values后拼接字符串,大批量数据更新同样也可以拼接字符串,只是方式稍微有点不同,直接看代码。

<?php
include_once ‘../admin/include.php’;
$info=$_SESSION[‘info’];
$chk22=$_POST[‘chk22’];
$chk11=$_POST[‘chk11’];
// echo json_encode($chk11);
$ids = implode(‘,’, array_keys($chk22));//获取要修改的条件列值
$sql = “UPDATE state SET result = CASE flag “;//根据flag条件列更新result值
foreach ($chk22 as $id => $ordinal) {
$sql .= sprintf(“WHEN %d THEN %d “, $id, $ordinal);//根据条件列循环拼接字符串
}
$sql .= “END WHERE flag IN ($ids) and info=’$info'”;//设置条件列取值范围和更新条件
if(mysql_query($sql,$conn)){
echo “11”;//传回自定义状态数据
}else{
echo “12”;
}
mysql_close($conn);


Leave a Reply

Your email address will not be published. Required fields are marked *