PHP MySQL


Create a new file called:   dbClass.php

  1. class Db {
  2.     // The database connection
  3.     protected static $connection;
  4.  
  5.     /**
  6.      * Connect to the database
  7.      * 
  8.      * @return bool false on failure / mysqli MySQLi object instance on success
  9.      */
  10.     public function connect() {    
  11.         // Try and connect to the database
  12.         if(!isset(self::$connection)) {
  13.             // Load configuration as an array. Use the actual location of your configuration file
  14.             $config = parse_ini_file('./config.ini');
  15.             self::$connection = newmysqli('localhost',$config['username'],$config['password'],$config['dbname']);
  16.         }
  17.  
  18.         // If connection was not successful, handle the error
  19.         if(self::$connection === false) {
  20.             // Handle error - notify administrator, log to a file, show an error screen, etc.
  21.             return false;
  22.         }
  23.         return self::$connection;
  24.     }
  25.  
  26.     /**
  27.      * Query the database
  28.      *
  29.      * @param $query The query string
  30.      * @return mixed The result of the mysqli::query() function
  31.      */
  32.     public function query($query) {
  33.         // Connect to the database
  34.         $connection = $this -> connect();
  35.  
  36.         // Query the database
  37.         $result = $connection -> query($query);
  38.  
  39.         return $result;
  40.     }
  41.  
  42.     /**
  43.      * Fetch rows from the database (SELECT query)
  44.      *
  45.      * @param $query The query string
  46.      * @return bool False on failure / array Database rows on success
  47.      */
  48.     public function select($query) {
  49.         $rows = array();
  50.         $result = $this -> query($query);
  51.         if($result === false) {
  52.             return false;
  53.         }
  54.         while ($row = $result -> fetch_assoc()) {
  55.             $rows[] = $row;
  56.         }
  57.         return $rows;
  58.     }
  59.  
  60.     /**
  61.      * Fetch the last error from the database
  62.      * 
  63.      * @return string Database error message
  64.      */
  65.     public function error() {
  66.         $connection = $this -> connect();
  67.         return $connection -> error;
  68.     }
  69.  
  70.     /**
  71.      * Quote and escape value for use in a database query
  72.      *
  73.      * @param string $value The value to be quoted and escaped
  74.      * @return string The quoted and escaped string
  75.      */
  76.     public function quote($value) {
  77.         $connection = $this -> connect();
  78.         return "'" . $connection -> real_escape_string($value) . "'";
  79.     }
  80. }


Using PHP with MySQL – The Right Way

https://www.binpress.com/using-php-with-mysql/




Hints and Tips: