2012-10-09 11 views
5

私が知りたいのは、mysqliのprepare,execute、およびrollbackを一緒に使用できるかどうかです。Mysqliの準備、実行、ロールバックを併用できますか?

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

これを行うことができますか?上記のコードにループがあり、変数が新しいデータを取得すると仮定します。

+0

試しましたか? –

+0

あなたはあなたが/できなかったと思いますか? –

+0

私はそれを試しましたが、その結果は不明です。それが私が求めている理由です。 PHPのマニュアルは、準備、実行、およびロールバックの両方が同時に機能する場合は何も言わない。誰もが試してみたり、それを働かせたりすることはありませんか? –

答えて

0

これを処理する最善の方法は、例外(常に、PHPのエラー/警告のように)です。単にcommit()コールが失敗する可能性もあります。 finallyは、より新しいPHPバージョンでのみ利用可能です。

<?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); 
} 
関連する問題