问题描述
- mysqli中执行多条语句同时事物处理
- <?php
$mysqli=new mysqli(""localhost""root""root""bookstore"");
if($mysqli->connect_error){
echo ""link bookstore database fail:"".$mysqli->connect_error;
}
// $mysqli->autocommit(0);
$sqls=""create table zh(id int auto_increment primary keyname varchar(60) not null default ''ye double not null default'0.00')type=InnoDB;"";
$sqls=""insert into zh(idnameye)values('1''zhangsan''2000');"";
$sqls.=""insert into zh (nameye) values('lisi'3000);"";
if($result=$mysqli->multi_query($sqls)){
echo ""zh database operation success"".""
"";
echo $mysqli->affected_rows.""
"";
}else{
echo ""database link fail:"".$mysqli->errno.""fail error:"".$mysqli->error.""
"";
}
// $mysqli=new mysqli(""localhost""root""root""bookstore"");
$mysqli->autocommit(0);
$error=true;
$price=50;
$sql=""update zh set ye=ye-{$price} where name='zhangsan'"";
$results=$mysqli->query($sql);
if(!$results){
$error=false;
echo""zhangsan transfer failed"".""
"";
}else{
echo $mysqli->affected_rows.""
"";
if($mysqli->affected_rows==0){
$error=false;
echo ""zhangsan money not have change"".""
"";
}else{
echo ""zhangsan money transfer out success"".""
"";
}
}
$sql=""update zh set ye=ye+{$price} where name='lisi'"";
$results=$mysqli->query($sql);
if(!$results){
$error=false;
echo ""transfer money failed for lisi"".""
"";
}else{
echo $mysqli->affected_rows.""
"";
if($mysqli->affected_rows==0){
$error=false;
echo ""lisi money has not change"".""
"";
}else{
echo ""lisi money transfer into success"".""
"";
}
}
if($error){
echo ""transfer success"".""
"";
$mysqli->commit();
}else{
echo ""transfer failed"".""
"";
$mysqli->rollback();
}
$mysqli->autocommit(1);
$mysqli->close();
时间: 2025-01-21 02:34:47