$datas = $_POST['datas'];
$datas = json_decode($datas, true);
// 构建批量更新的 SQL 语句
$updateSql = "UPDATE orderlist SET payid = ?, paycol = '1',orderstatus='4' WHERE orderid = ? AND codename = ?";
$updateStmt = $link->prepare($updateSql);
$updateStmt->bind_param('sss', $payid, $oid, $code);
// 构建批量查询的 SQL 语句
$selectSql = "SELECT SUM(thmoney) FROM orderth WHERE oid = ? AND isth = 't'";
$selectStmt = $link->prepare($selectSql);
$selectStmt->bind_param('s', $oid);
$selectStmt->bind_result($money);
// 循环更新orderlist,同时查询是否有退款,有:统计退款价值
foreach ($datas as $item) {//循环了两次
$opayacc += $item['allmoney']; //订单金额累加
$code = $item['codename'];
$oid = $item['orderid'];
$updateStmt->execute();//*****这里只更新了第一条数据!为什么???
$selectStmt->execute();
if ($selectStmt->fetch()) {//*****这里,循环了两次,取到了所有数据并累加,成功了
$thmoney += floatval($money);
} else {
$thmoney += 0;
}
}
//$updateStmt->close();
$selectStmt->close();
这是前端传送的datas
$datas = '[{"id":96,"codename":"LL","orderid":"DD230831321934","allmoney":5104.7},{"id":93,"codename":"LL","orderid":"DD230830760415","allmoney":177}]';
为什么在循环中,循环了两次,update只更新了一条数据呢?
【以下回答由 GPT 生成】
问题所在是因为每次循环时,都使用了相同的预处理语句和绑定参数,导致只有第一条数据被更新。解决问题的方法是,在每次循环之前重新绑定参数,并使用不同的预处理语句。
以下是修改后的代码:
$datas = $_POST['datas'];
$datas = json_decode($datas, true);
// 构建批量查询的 SQL 语句
$selectSql = "SELECT SUM(thmoney) FROM orderth WHERE oid = ? AND isth = 't'";
$selectStmt = $link->prepare($selectSql);
$selectStmt->bind_param('s', $oid);
$selectStmt->bind_result($money);
// 循环更新orderlist,同时查询是否有退款,有:统计退款价值
foreach ($datas as $item) {
$opayacc += $item['allmoney']; //订单金额累加
$code = $item['codename'];
$oid = $item['orderid'];
// 构建批量更新的 SQL 语句
$updateSql = "UPDATE orderlist SET payid = ?, paycol = '1', orderstatus='4' WHERE orderid = ? AND codename = ?";
$updateStmt = $link->prepare($updateSql);
$updateStmt->bind_param('sss', $payid, $oid, $code);
$updateStmt->execute(); // 更新数据库
$selectStmt->execute(); // 查询
if ($selectStmt->fetch()) {
$thmoney += floatval($money); // 累加退款金额
} else {
$thmoney += 0;
}
$updateStmt->close(); // 关闭预处理语句
}
$selectStmt->close();
修改后的代码在循环内部重新绑定参数,并创建了不同的预处理语句。这样就保证了每次循环都使用正确的参数来更新数据库。同时,关闭了预处理语句,以释放资源。
这样就可以正确更新整个数组中的数据了。
【相关推荐】