如何在php/mysql中使用事务 [英] How to use transaction in php/mysql
问题描述
我正在使用php/mysql.我知道mysql中的事务,但是不能在我的脚本中使用.以下是我的脚本,如何在代码中使用php事务.即BEGIN,ROLLBACK,COMMIT
i am using php/mysql. i know about the transaction in mysql but can't use in my script. below is my script how can i use php transaction in my code.i.e BEGIN, ROLLBACK, COMMIT
foreach($json_a['shop'] as $jsondata=>$json)
{
if($json['category']==='product')
{
$name_product=$json['name'];
$query1="insert into product(id,name,user_id)values('','" . mysql_real_escape_string($name_product). "','1')";
$result1=mysql_query($query1) or die("error in query".mysql_errno());
//echo "success...!";
$product++;
}
else
if($json['category']==='order')
{
$name_order=$json['name'];
$query2="insert into order(id,name,user_id)values('','" . mysql_real_escape_string($name_order). "','1')";
$result2=mysql_query($query2) or die("error in query".mysql_errno());
$order++;
}
else
if($json['category']==='sale')
{
$name_sale=$json['name'];
$query3="insert into sale(id,name,user_id)values('','" . mysql_real_escape_string($name_sale). "','1')";
$result3=mysql_query($query3) or die("error in query".mysql_errno());
$sale++;
}
}
推荐答案
只需发出mysql_query('START TRANSACTION');
,并在每次插入时检查错误.如果其中之一没有成功,则不执行任何其余查询就立即发出ROLLBACK.如果一切正常,请发出COMMIT.
Simply issue mysql_query('START TRANSACTION');
and check for errors at every one of your inserts. If one of them doesn't succeed issue a ROLLBACK immediately without doing any of the remaining queries. If everything goes fine with all of them issue a COMMIT.
将它们放在try-catch块中可能会更容易,以避免在if-else中使用过多级别的嵌套.
It may be easier to put them in a try-catch block to avoid using too many levels of nesting with if-else.
// START TRANSACTION
try{
// INSERT 1
if(failed)
throw new Exception();
// INSERT 2
if(failed)
throw new Exception();
// INSERT 3
if(failed)
throw new Exception();
// COMMIT
}
catch(Exception $e){
// ROLLBACK
}
您可能还需要研究PHP的 PDO扩展.交易是其功能的一部分.
You may also want to take a look into PHP's PDO extension. Transactions are part of its features.
这篇关于如何在php/mysql中使用事务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!