Mysql INSERT和DELETE在单个语句中依赖于彼此

时间:2015-05-17 17:22:09

标签: php mysql database mysqli

我有以下两个问题。第二个查询取决于第一个查询。

$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");
   }
}

我们可以在一个语句中执行这两个查询,以便两个查询相互依赖。
如果INSERT查询失败,DELETE查询也会失败它的执行以及DELETE查询在查询中失败INSERTION首先失败。

感谢

4 个答案:

答案 0 :(得分:2)

如果我很了解您的需求,只需使用交易即可。 在插入之前运行此查询:

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

答案 1 :(得分:1)

如果query2失败,则不检查query1。

fvh.js

答案 2 :(得分:0)

您可以使用事务,如果任何查询失败,则调用rollback,否则提交

答案 3 :(得分:0)

我找到了最佳解决方案。
扩展@Luki的想法我写了下面的代码,它给了我太多满意的答案。首先使用以下功能。

function multi_statement()
{
    global $conn;
    $total_args = func_get_args();
    $args = implode($total_args,";");
    $args = "begin;".$args.";commit;";
    $number = 0;
    if($conn->multi_query($args))
    {
        do
        {
            if ($conn->more_results())
            {
                $number++;
            }
        }
        while($conn->next_result());
    }
    if($number < (count($total_args)+1))
    {
        $conn->query('rollback');
        echo "Sorry..!!! Error found in Query no:".$number;
    }
    else
    {
        echo "All queries executed successfully";
    }
}

然后我用语句数调用了函数,所有这些语句都相互依赖。如果在任何查询中出现错误,则不会在数据库中发生任何更改。

    $statement1 = "INSERT INTO `pic_gall`.`admin` (`admin_id`, `username`, `password`) VALUES (NULL, 'as1', 'as1')";
    $statement2 = "INSERT INTO `pic_gall`.`admin` (`admin_id`, `username`, `password`) VALUES (NULL, 'as2', 'as2')";
    $statement3 = "INSERT INTO `pic_gall`.`admin` (`admin_id`, `username`, `password`) VALUES (NULL, 'as3', 'as3')";
    $statement4 = "INSERT INTO `pic_gall`.`admin` (`admin_id`, `username`, `password`) VALUES (NULL, 'as4', 'as4')";
    $statement5 = "DELETE from user where user_id = '12'";
multi_statement($statement1,$statement2,$statement3,$statement4,$statement5);