2017-07-19 3 views
-4

Ich habe eine Abfrage, die 'INSERT', 'DELETE' und 'UPDATE' Anweisung enthält. Jetzt ist meine Frage: „Ist es möglich, keine Anweisung ausführen, wenn eine andere der Anweisung fehlgeschlagen ist“Abfrage ausführen, wenn alle Anweisungen erfolgreich sind

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

Hier finden Sie aktuelle MySQL-Transaktionen. – BenRoob

Antwort

0

Sie müssen ein MySQL transactions verwenden. Es ermöglicht Ihnen, alle Änderungen rückgängig zu machen (die bei der Transaktion vorgenommen wurden), wenn etwas schief geht (z. B. Sie haben einen Fehler erhalten).

Einfaches Beispiel:

<?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(); 
?> 
Verwandte Themen