我有以下两个问题。第二个查询依赖于第一个查询。
$query1 = mysql_query("Insert into table_one set ---- ");
if($query1)
{
$query2 = mysql_query("delete from table_two where condition---");
if($query2)
{
$message = "both queries executed successfully";
}
else
{
$del = mysql_query("delete record inserted by $query1");
}
}我们能否在一条语句中执行这两个查询,以便这两个查询相互依赖。
如果插入查询失败,删除查询也会失败它的执行,以及如果删除查询失败插入查询第一次失败。
谢谢
发布于 2015-05-17 17:28:00
如果我很好地理解您需要什么,只需使用事务。在插入之前运行此查询:
mysql_query('begin');然后,如果一切顺利,提交事务:
mysql_query('commit');如果发生任何故障,您可以回滚所做的每一项更改:
mysql_query('rollback');注意,对于MySQL,MyISAM引擎不支持事务回滚,所以使用InnoDB。
在这里阅读更多关于事务的信息:https://dev.mysql.com/doc/refman/5.0/en/commit.html
使用代码的示例:
<?PHP
mysql_query('begin'); //start transaction
$query1 = mysql_query("Insert into table_one set ---- ");
if($query1)
{
$query2 = mysql_query("delete from table_two where condition---");
if($query2)
{
mysql_query('commit'); //both queries went fine, so let's save your changes and end the transaction
$message = "both queries executed successfully";
}
else
{
mysql_query('rollback'); //query2 failed, so let's rollback changes made by query1 and end the transaction
}
}
else
mysql_query('rollback'); //query1 failed, so let's end the transaction发布于 2015-05-17 17:43:53
如果query2失败了,它就不会检查query1。
$query1 = mysql_query("Insert into table_one set ---- ");
$query2 = mysql_query("delete from table_two where condition---");
if( $query2 && $query1)
{
$message = "both queries executed successfully";
}
else if(!$query2)
{
$del = mysql_query("delete record inserted by $query1");
}发布于 2015-05-17 17:27:03
您可以使用事务,如果任何查询失败,则调用回滚,否则提交。
https://stackoverflow.com/questions/30289786
复制相似问题