Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- The best practise when to use PHP exception handling
- <?php public function index() {
- $this->database->query("SELECT user_name, FROM test WHERE user_name = :user_name");
- $this->database->execute_query("jim");
- $this->view->data = $this->database->fetch_query();
- ?>
- <?php
- class DB {
- private $datasourcename;
- private $user;
- private $password;
- private $connection;
- private $prepare;
- private $query;
- function __construct($dsn, $user, $password) {
- $this->datasourcename = $dsn;
- $this->user = $user;
- $this->password = $password;
- $this->connection = new PDO($this->datasourcename, $this->user, $this->password);
- }
- public function query($query) {
- $this->query = $query;
- try {
- if (empty($query)) {
- throw new Exception("The query is empty");
- return false;
- }
- } catch (Exception $e) {
- echo 'Caught exception: ', $e->getMessage(), "<br/>";
- }
- if (strstr($query, ":") == FALSE) {
- return $this->connection->query($query);
- } else {
- $this->prepare = $this->connection->prepare($query);
- }
- }
- public function execute_query($valarg = array()) {
- try {
- if (empty($valarg)) {
- throw new Exception("There are no values in the execute query function");
- return false;
- }
- if (is_array($valarg) == false) {
- throw new Exception("The values inserted are not in an array");
- return false;
- } else {
- $query = $this->query;
- $paramkeys = array();
- $paramArr = array();
- if (strstr($query, ":")) {
- preg_match_all("/:(w+)/", $query, $paramkeys);
- $paramArr = array_combine($paramkeys[0], $valarg);
- $this->prepare->execute($paramArr);
- }
- }
- } catch (Exception $e) {
- echo 'Caught exception: ', $e->getMessage(), "<br/>";
- }
- }
- public function fetch_query() {
- try {
- if($this->execute_query() == false) {
- throw new Exception("Sorry you need to fix this first");
- }
- if($this->query() == false) {
- throw new Exception("Sorry you need to fix this first");
- }
- else {
- $result = $this->prepare->fetch(PDO::FETCH_ASSOC);
- return $result;
- }
- }
- catch (Exception $e) {
- echo 'Caught exception: ', $e->getMessage(), "<br/>";
- }
- }
- }
- ?>
Add Comment
Please, Sign In to add comment