2017-07-19 66 views
-4

我有一個包含'插入','刪除'和'更新'語句的查詢。現在的問題是「是否有可能不聲明運行,如果任何其他語句的失敗」運行查詢如果所有的語句都成功

$sql=" START Transaction INSERT statement; DELETE statement; UPDATE statement; COMMIT"; 
+2

看一看MySQL的交易。 – BenRoob

回答

0

您必須使用MySQL transactions。如果出現問題(例如,出現錯誤),它將允許您回滾所有更改(這是對事務進行的更改)。

簡單的例子:

<?php 
$all_query_ok=true; // our control variable 
$mysqli = new mysqli("localhost", "user", "pass", "dbname"); 

/* check connection */ 
if (mysqli_connect_errno()) { 
    printf("Connect failed: %s\n", mysqli_connect_error()); 
    exit(); 
} 

/* disable autocommit */ 
$mysqli->autocommit(FALSE); 

//we make 4 inserts, the last one generates an error 
//if at least one query returns an error we change our control variable 
$mysqli->query("INSERT INTO myCity (id) VALUES (100)") ? null : $all_query_ok=false; 
$mysqli->query("INSERT INTO myCity (id) VALUES (200)") ? null : $all_query_ok=false; 
$mysqli->query("INSERT INTO myCity (id) VALUES (300)") ? null : $all_query_ok=false; 
$mysqli->query("INSERT INTO myCity (id) VALUES (100)") ? null : $all_query_ok=false; //duplicated PRIMARY KEY VALUE 

//now let's test our control variable 
$all_query_ok ? $mysqli->commit() : $mysqli->rollback(); 

$mysqli->close(); 
?>