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

标题: 原生phpmysqli使用事务示例 [打印本页]

作者: 追影    时间: 2023-12-25 16:03
标题: 原生phpmysqli使用事务示例
  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. }
复制代码







欢迎光临 大米CMS官网论坛,大米站长联盟,大米站长之家,大米开发者社区 (https://www.damicms.com/bbs/) Powered by Discuz! X3.1