为了账号安全,请及时绑定邮箱和手机立即绑定

MySQL 多查询 InnoDB

MySQL 多查询 InnoDB

PHP
慕容708150 2022-07-29 10:27:58
我是 InnoDB 事务的新手。我正在学习,但我对此有疑问。<?phpinclude_once("../../../../../wp-config.php");global $wpdb;$cats_table     = $wpdb->prefix . "jb_menu_groups";$relation       = $wpdb->prefix . "jb_relations";$mysqli = new mysqli($wpdb->dbhost, $wpdb->dbuser, $wpdb->dbpassword, $wpdb->dbname);if ($mysqli -> connect_errno) {    echo "Failed to connect to MySQL: " . $mysqli -> connect_error;    exit();}// Turn autocommit off$mysqli -> autocommit(FALSE);$mysqli -> query("DELETE FROM $cats_table WHERE id=6");$mysqli -> query("DELETE FROM $relation WHERE groupid=3");// Commit transactionif (!$mysqli -> commit()) {  echo "Commit transaction failed";  exit();}$mysqli -> rollback();$mysqli -> close();?>如果我创建一个错误的查询来测试提交和回滚,则代码会成功运行另一个查询。如何在一个事务中执行多个查询,如果一个查询有错误,请回滚并取消事务?
查看完整描述

1 回答

?
慕妹3146593

TA贡献1820条经验 获得超9个赞

我个人只使用 PDO 和事务,但这就是它应该如何使用 mysqli:


// start the transaction

$mysqli->autocommit(false);


$catQuery = $mysqli->query("DELETE FROM $cats_table WHERE id=6");

$relationQuery = $mysqli->query("DELETE FROM $relation WHERE groupid=3");


if ($catQuery && $relationQuery) {

    // in case the db server confirms the correctness of the queries, commit the transaction

    $mysqli->commit();

} else {

    // something went wrong

    $mysqli->rollback();

}


// don't forget to reset the transaction mode again, in case your app isn't ending here

$mysqli->autocommit(true);

请确保不要CREATE, ALTER or DROP在事务中包含语句,因为这将立即提交更改。


查看完整回答
反对 回复 2022-07-29
  • 1 回答
  • 0 关注
  • 116 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号