2012-10-09 6 views
5

mysqli의 prepare, executerollback을 함께 사용할 수 있는지 알고 싶습니다.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); 
} 
관련 문제