MySQLi Prepared Statements and Transactions

China☆狼群 提交于 2019-12-31 22:22:15

问题


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 statement 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?


回答1:


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.



来源:https://stackoverflow.com/questions/5372453/mysqli-prepared-statements-and-transactions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!