Guest User

Untitled

a guest
Jul 27th, 2018
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.68 KB | None | 0 0
  1. The best practise when to use PHP exception handling
  2. <?php public function index() {
  3.  
  4. $this->database->query("SELECT user_name, FROM test WHERE user_name = :user_name");
  5.  
  6. $this->database->execute_query("jim");
  7.  
  8. $this->view->data = $this->database->fetch_query();
  9.  
  10. ?>
  11.  
  12. <?php
  13.  
  14. class DB {
  15.  
  16. private $datasourcename;
  17. private $user;
  18. private $password;
  19. private $connection;
  20. private $prepare;
  21. private $query;
  22.  
  23. function __construct($dsn, $user, $password) {
  24.  
  25. $this->datasourcename = $dsn;
  26. $this->user = $user;
  27. $this->password = $password;
  28.  
  29.  
  30. $this->connection = new PDO($this->datasourcename, $this->user, $this->password);
  31. }
  32.  
  33. public function query($query) {
  34.  
  35. $this->query = $query;
  36. try {
  37. if (empty($query)) {
  38.  
  39. throw new Exception("The query is empty");
  40. return false;
  41. }
  42. } catch (Exception $e) {
  43. echo 'Caught exception: ', $e->getMessage(), "<br/>";
  44. }
  45. if (strstr($query, ":") == FALSE) {
  46. return $this->connection->query($query);
  47. } else {
  48.  
  49. $this->prepare = $this->connection->prepare($query);
  50. }
  51. }
  52.  
  53. public function execute_query($valarg = array()) {
  54.  
  55. try {
  56. if (empty($valarg)) {
  57.  
  58. throw new Exception("There are no values in the execute query function");
  59. return false;
  60. }
  61. if (is_array($valarg) == false) {
  62.  
  63. throw new Exception("The values inserted are not in an array");
  64. return false;
  65. } else {
  66.  
  67. $query = $this->query;
  68. $paramkeys = array();
  69. $paramArr = array();
  70.  
  71. if (strstr($query, ":")) {
  72.  
  73.  
  74. preg_match_all("/:(w+)/", $query, $paramkeys);
  75.  
  76. $paramArr = array_combine($paramkeys[0], $valarg);
  77.  
  78.  
  79. $this->prepare->execute($paramArr);
  80. }
  81. }
  82. } catch (Exception $e) {
  83. echo 'Caught exception: ', $e->getMessage(), "<br/>";
  84. }
  85. }
  86.  
  87. public function fetch_query() {
  88.  
  89. try {
  90. if($this->execute_query() == false) {
  91.  
  92. throw new Exception("Sorry you need to fix this first");
  93. }
  94.  
  95. if($this->query() == false) {
  96.  
  97. throw new Exception("Sorry you need to fix this first");
  98. }
  99. else {
  100.  
  101. $result = $this->prepare->fetch(PDO::FETCH_ASSOC);
  102.  
  103. return $result;
  104. }
  105. }
  106. catch (Exception $e) {
  107. echo 'Caught exception: ', $e->getMessage(), "<br/>";
  108. }
  109.  
  110.  
  111. }
  112.  
  113. }
  114.  
  115. ?>
Add Comment
Please, Sign In to add comment