如何在php / mysql中使用事务
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
我正在使用php / mysql。我知道mysql中的事务但不能在我的脚本中使用。下面是我的脚本我怎么能在我的code.i.e BEGIN,ROLLBACK,COMMIT中使用php事务
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++;
}
}
3 个解决方案
#1
13
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.
简单地发出mysql_query('START TRANSACTION');并检查每个插入的错误。如果其中一个没有成功,则立即发出ROLLBACK而不执行任何剩余的查询。如果一切顺利,所有人都会发出一个COMMIT。
It may be easier to put them in a try-catch block to avoid using too many levels of nesting with if-else.
将它们放在try-catch块中可能更容易,以避免使用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
}
You may also want to take a look into PHP's PDO extension. Transactions are part of its features.
您可能还想了解PHP的PDO扩展。交易是其功能的一部分。
更多相关文章
- imagecreatetruecolor()在symfony中不起作用,但如果作为php脚本运行
- php-fpm通过request_slowlog_timeout检查哪个脚本执行时间长
- 显示长期运行的PHP脚本的进展。
- PHP基础之脚本传参
- phpBB3导入帖子的Python脚本
- PHP脚本在我的Wordpress文件中。请解码或帮助我删除它。
- AJAX调用在JavaScript中运行PHP脚本
- MySQL的事务隔离级别以及设置
- 通过Bash脚本语言逃避MYSQL命令行。