Guest User

Untitled

a guest
Jul 20th, 2018
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.97 KB | None | 0 0
  1. public function prepareExecFetch() { ... }
  2.  
  3. public function prepareExec() { ... }
  4.  
  5. public function fetch() { ... }
  6.  
  7. $stmt1 = $pdo->prepare('...');
  8. $stmt1->execute(array('...' => '...'));
  9. $r1 = $stmt1->fetch(PDO::FETCH_ASSOC);
  10.  
  11. <?php
  12. class DB {
  13. private $host;
  14. private $name;
  15. private $charset;
  16. private $user;
  17. private $password;
  18.  
  19. // I wonder how could I store all the statements here, using the
  20. // $stmt1 = ...; $stmt2 = ...; wouldn't work cause it has to be
  21. // dymanic and I can't create new properties inside any method
  22. private $stmts = [];
  23.  
  24. // Not using static modifier because if there was another instance of this
  25. // class, then $stmtCounter variable should be resetted again to 0
  26. private $stmtCounter = 0;
  27.  
  28. public function __construct(string $host, string $name, string $charset,
  29. string $user, string $password) {
  30. $this->host = $host;
  31. $this->name = $name;
  32. $this->charset = $charset;
  33. $this->user = $user;
  34. $this->password = $password;
  35.  
  36. $pdo = new PDO('mysql:host=' . $this->host . '; dbname=' . $this->name . ';
  37. charset=' . $this->charset, $this->user, $this->password);
  38.  
  39. // While false, PDO will take advantage of the native prepared statement
  40. // functionality
  41. $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
  42.  
  43. // In exception mode, if there is an error in SQL, PDO will throw
  44. // exceptions and the script will stop running
  45. $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  46. }
  47.  
  48. public function execPrepareFetch(string $stmt, array $execParams) {
  49. $this->stmtCounter++;
  50. array_push($this->stmts, $stmt . $this->stmtCounter);
  51. }
  52. }
  53.  
  54. // This way by instantiating multiple instances we can easily work with multiple
  55. //databases
  56. $db = new DB(DB_HOST, DB_NAME, DB_CHARSET, DB_USER, DB_PASSWORD);
  57. $db->execPrepareFetch('$stmt', [':user' => 'some value']);
Add Comment
Please, Sign In to add comment