Guest User

Untitled

a guest
Sep 20th, 2018
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.08 KB | None | 0 0
  1. <?php
  2. const DBHOST = 'localhost';
  3. CONST DBPORT = '3306';
  4. const DBNAME = 'test';
  5. const DBUSER = 'root';
  6. const DBPASS = '123456';
  7.  
  8. withTransaction(function(PDO $db) {
  9. $insertReport = $db->prepare('INSERT INTO tbl_report (`uid`,`type`,`status`,`target_id`,`content`,`datetime`) VALUES (?,?,?,?,?,?)');
  10. $insertAttach = $db->prepare('INSERT INTO tbl_report_attach (`rid`,`type`,`usage`,`url`,`datetime`) VALUES (?,?,?,?,?)');
  11.  
  12. $selectCommReports = $db->prepare('SELECT * from tbl_comm_report ORDER BY id DESC');
  13. $selectCommReportAttaches = $db->prepare('SELECT * from tbl_comm_report_attach WHERE rid = ?');
  14. $selectCommReports->execute();
  15. foreach($selectCommReports->fetchAll() as $commReport) {
  16. $insertReport->execute([
  17. $commReport['uid'],
  18. 0,
  19. $commReport['status'],
  20. $commReport['fuid'],
  21. $commReport['content'],
  22. $commReport['datetime'],
  23. ]);
  24.  
  25. $lastId = $db->lastInsertId();
  26. $selectCommReportAttaches->execute([$commReport['id']]);
  27. foreach($selectCommReportAttaches->fetchAll() as $commAttach) {
  28. $insertAttach->execute([
  29. $lastId,
  30. $commAttach['type'],
  31. $commAttach['usage'],
  32. $commAttach['url'],
  33. $commAttach['datetime'],
  34. ]);
  35. }
  36. $selectCommReportAttaches->closeCursor();
  37. }
  38. $selectCommReports->closeCursor();
  39. });
  40.  
  41.  
  42. function withTransaction($func) {
  43. withDb(function(PDO $db) use ($func) {
  44. $db->beginTransaction();
  45. try {
  46. $func($db);
  47. $db->commit();
  48. } catch (Exception $e) {
  49. $db->rollBack();
  50. throw $e;
  51. }
  52. });
  53. }
  54.  
  55. function withDb($func) {
  56. try {
  57. $dbh = new PDO(sprintf('mysql:host=%s;dbname=%s;charset=UTF8;port=%s', DBHOST, DBNAME, DBPORT), DBUSER, DBPASS);
  58. $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  59.  
  60. $func($dbh);
  61.  
  62. $dbh = null;
  63. } catch (PDOException $e) {
  64. print "Error!: " . $e->getMessage() . PHP_EOL;
  65. die();
  66. }
  67. }
Add Comment
Please, Sign In to add comment