问题描述
我有一个项目列表,我想插入包含 INSERT 查询的表中。 我正在使用 MysqL 和 PHP。
我收到带有 POST 的练习名称列表(用逗号分隔),并希望将它们保存在数据库中,将它们关联到一个 ID(我也从 POST 中收到)。
我想准备一个唯一的查询并只运行一次,而不是运行多个 INSERT 查询,以便整个查询运行或失败。
这是我的代码。
$exList= $_REQUEST['exList'];
$routineID = $_REQUEST['routineID'];
$arrayEx = explode(',',$exList);
$countEx=count($arrayEx);
$placeholdersEx = implode(',array_fill(0,$countEx,'?'));
$bindStrEx = str_repeat('si',$countEx);
$queryEx = str_repeat('INSERT INTO exercises_x_routines(exerciseID,routineID) VALUES(?,?);',$countEx);
$arrayRoutine = array_fill(0,$routineID);
$stmt = MysqLi_prepare($con,substr($queryEx,-1));
MysqLi_stmt_bind_param($stmt,$bindStrEx,...$arrayEx,...$arrayRoutine));
if (!MysqLi_stmt_execute($stmt))
{
//print MysqLi_error($con);
$output[]=array("code" => 3003,"error" => MysqLi_error($con));
print(json_encode($output));
MysqLi_close($con);
exit;
}
但是,我不知道为什么但是查询执行不成功并且我没有从 MysqLi_error 得到任何错误描述。
解决方法
您不能准备多个查询。相反,您可以准备一次查询并执行多次:
{!frange l=0.0 u=10000.0}sub(field(payment_double_mv,max),product(field(payment_double_mv,min),min(sub(field(price_double),2500),min(max(0.000000,field(deposit_double_mv,min)),max)))))
如果您想有效地使其成为单个插入,并且在任何插入失败时不更改表,您可以使用事务:
$exList= $_REQUEST['exList'];
$routineID = $_REQUEST['routineID'];
$arrayEx = explode(',',$exList);
$queryEx = 'INSERT INTO exercises_x_routines(exerciseID,routineID) VALUES(?,?)';
$stmt = $con->prepare($queryEx);
$stmt->bind_param('si',$ex,$routineID);
foreach ($arrayEx as $ex) {
if (!$stmt->execute()) {
$output[]=array("code" => 3003,"error" => $con->error);
print(json_encode($output));
$con->close();
exit;
}
}