$json = file_get_contents("php://input"); $res = json_decode($json,true); var_dump($res); foreach($res as $value){ $jz_num = $value['卷宗号']; $aj_num = $value['案卷号']; $gzy = $value['公证员']; $gzsx = $value['公证事项']; $money = $value['金额']; $year = $value['年号']; $ml =$value['目录号']; $save =$value['保管期限']; $storage_time=date('Y-m-d h:i:s',time()); $month_time=date('m'); $query = "INSERT INTO book (title,aj_num, publish_year,directory,state,save_time,storage_time,author,publisher,price,month) VALUES ('$jz_num','$aj_num','$year','$ml','在库','$save','$storage_time','$gzy','$gzsx','$money','$month_time')"; //$conn->query($query); mysqli_query($conn,$query) or die("添加失败".mysqli_error()); } 帮优化代码防止重复插入
时间: 2023-08-31 17:52:31 浏览: 245
可以先查询数据库中是否已存在对应的卷宗号和案卷号,如果已存在则不插入,否则再执行插入操作。可以使用如下代码进行优化:
$json = file_get_contents("php://input");
$res = json_decode($json,true);
foreach($res as $value){
$jz_num = $value['卷宗号'];
$aj_num = $value['案卷号'];
$gzy = $value['公证员'];
$gzsx = $value['公证事项'];
$money = $value['金额'];
$year = $value['年号'];
$ml =$value['目录号'];
$save =$value['保管期限'];
$storage_time=date('Y-m-d h:i:s',time());
$month_time=date('m');
$query = "SELECT COUNT(*) FROM book WHERE title = '$jz_num' AND aj_num = '$aj_num'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_array($result);
if ($row[0] == 0) {
$insert_query = "INSERT INTO book (title,aj_num,publish_year,directory,state,save_time,storage_time,author,publisher,price,month) VALUES ('$jz_num','$aj_num','$year','$ml','在库','$save','$storage_time','$gzy','$gzsx','$money','$month_time')";
mysqli_query($conn,$insert_query) or die("添加失败".mysqli_error());
}
}
这样就能避免重复插入了。
阅读全文
相关推荐


















