2012-10-09 29 views
5

Tutto quello che voglio sapere è se è possibile utilizzare mysqli prepare, execute e rollback insieme?Puoi usare Mysqli per preparare, eseguire e ripristinare insieme?

$m = new mysqli($dbhost,$dbuser,$dbpassword,$dbname); 

$m->autocommit(FALSE); 
$stmt = $m->prepare("INSERT `table` (`name`,`gender`,`age`) VALUES (?,?,?)"); 
$stmt->bind_param("ssi", $name, $gender, $age); 
$query_ok = $stmt->execute(); 

$stmt = $m->prepare("INSERT `table` (`name`,`gender`,`age`) VALUES (?,?,?)"); 
$stmt->bind_param("ssi", $name, $gender, $age); 
if ($query_ok) {$query_ok = $stmt->execute();} 

if (!$query_ok) {$m->rollback();} else {$m->commit();} 

Puoi farlo? Supponiamo che il codice precedente abbia un ciclo e che le variabili ottengano nuovi dati al loro interno.

+0

Hai provato? –

+0

Cosa ti fa pensare che potresti/non potresti? –

+0

L'ho provato e non è chiaro sui risultati, motivo per cui lo sto chiedendo. La documentazione di PHP non dice nulla in alcun modo se preparare, eseguire e eseguire il rollback insieme. Qualcuno ha mai provato o ha funzionato? –

risposta

0

Il modo migliore per gestire questo è con le eccezioni (come sempre, dannatamente errore PHP/materiale di avviso). Semplicemente perché anche la nostra chiamata commit() potrebbe fallire. Si noti che finally è disponibile solo nelle versioni PHP più recenti.

<?php 

// Transform all errors to exceptions! 
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); 

try { 
    $connection = new \mysqli($dbhost, $dbuser, $dbpassword, $dbname); 
    $connection->autocommit(false); 

    $stmt = $connection->prepare("INSERT `table` (`name`, `gender`, `age`) VALUES (?, ?, ?)"); 
    $stmt->bind_param("ssi", $name, $gender, $age); 
    $stmt->execute(); 

    // We can simply reuse the prepared statement if it's the same query. 
    //$stmt = $connection->prepare("INSERT `table` (`name`, `gender`, `age`) VALUES (?, ?, ?)"); 

    // We can even reuse the bound parameters. 
    //$stmt->bind_param("ssi", $name, $gender, $age); 

    // Yet it would be better to write it like this: 
    /* 
    $stmt = $connection->prepare("INSERT `table` (`name`, `gender`, `age`) VALUES (?, ?, ?), (?, ?, ?)"); 
    $stmt->bind_param("ssissi", $name, $gender, $age, $name, $gender, $age); 
    */ 

    $stmt->execute(); 
    $stmt->commit(); 
} 
catch (\mysqli_sql_exception $exception) { 
    $connection->rollback(); 
    throw $exception; 
} 
finally { 
    isset($stmt) && $stmt->close(); 
    $connection->autocommit(true); 
} 
Problemi correlati