大米CMS官网论坛,大米站长联盟,大米站长之家,大米开发者社区

 找回密码
 注册大米会员

QQ登录

只需一步,快速开始

查看: 351|回复: 0
打印 上一主题 下一主题

原生phpmysqli使用事务示例

[复制链接]

500

主题

777

帖子

7655

积分

超级版主

Rank: 8Rank: 8

积分
7655

授权用户

跳转到指定楼层
楼主
发表于 2023-12-25 16:03:08 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
  1. <?php

  2. /* Tell mysqli to throw an exception if an error occurs */
  3. mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

  4. $mysqli = new mysqli("localhost", "my_user", "my_password", "world");

  5. /* The table engine has to support transactions */
  6. $mysqli->query("CREATE TABLE IF NOT EXISTS language (
  7. Code text NOT NULL,
  8. Speakers int(11) NOT NULL
  9. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");

  10. /* Start transaction */
  11. $mysqli->begin_transaction();

  12. try {
  13. /* Insert some values */
  14. $mysqli->query("INSERT INTO language(Code, Speakers) VALUES ('DE', 42000123)");

  15. /* Try to insert invalid values */
  16. $language_code = 'FR';
  17. $native_speakers = 'Unknown';
  18. $stmt = $mysqli->prepare('INSERT INTO language(Code, Speakers) VALUES (?,?)');
  19. $stmt->bind_param('ss', $language_code, $native_speakers);
  20. $stmt->execute();

  21. /* If code reaches this point without errors then commit the data in the database */
  22. $mysqli->commit();
  23. } catch (mysqli_sql_exception $exception) {
  24. $mysqli->rollback();

  25. throw $exception;
  26. }
复制代码


分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 分享分享
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册大米会员

本版积分规则

QQ|小黑屋|大米CMS社区 ( 蜀ICP备11002200号-2广告联系:广告联系 

Powered by 大米CMS

© 2010-2020 大米CMS Inc.

快速回复 返回顶部 返回列表