开发者

MySQLi Prepared Statements and Transactions

Is there a way to do transactions with prepared statements?

I mean can I use the following example with $mysqli->autocommit(FALSE); and $mysqli->commit( ); and $mysqli->rollback( );

//Preparing the statment

$insert_stmt=$mysqli->prepare("INSERT INTO x VALUES(?,?)")
or die($mysqli->error);

//associate variables with the input parameters

$insert_stmt->bind_param("is", $my_number,$my_string); //i=integer

//Execute the statem开发者_如何转开发ent multiple times....

for ($my_number = 1; $my_number <= 10; $my_number++) 
{
    $my_string="row ".$my_number;
    $insert_stmt->execute() or die ($insert_stmt->error);
}
$insert_stmt->close();

I have looked around but can't find any example of using prepared statements (not PDO): http://php.net/manual/en/mysqli.prepare.php with transactions, I only find examples like these mentioned here: http://book.opensourceproject.org.cn/lamp/mysql/mysqlstored/opensource/0596100892/mysqlspp-chp-13-sect-2.html where transactions and prepared statements are never inter-mixed.

Would it be wrong to use them together?


Prepared statements and transactions are unrelated techniques and technologies.

You may wish to issue the START TRANSACTION and COMMIT/ROLLBACK commands directly instead of using the dedicated methods. They are functionally equivalent.

For your loop, you'd issue the START TRANSACTION before your prepare, then your COMMIT after the loop exits. You probably should not try to open a transaction after a prepared statement has been started but before it's been executed.

For some reason, they didn't add a "start transaction" command in favor of turning off autocommit. It's one of those weird things about mysqli that makes me always recommend PDO instead. :) Opening a transaction implicitly turns off autocommit for the duration of the transaction.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜