Advertisement
Guest User

msqli

a guest
Jun 22nd, 2015
319
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.68 KB | None | 0 0
  1. <?php
  2.     defined('DB_SERVER') ? null : define("DB_SERVER", "localhost");
  3.     defined('DB_USER')   ? null : define("DB_USER", "root");
  4.     defined('DB_PASS')   ? null : define("DB_PASS", "*************");
  5.     defined('DB_NAME')   ? null : define("DB_NAME", "*************");
  6. ?>
  7.  
  8. <?php
  9.  
  10. class database extends mysqli {
  11.  
  12.     private $db;
  13.  
  14.     function __construct() {
  15.         $this->db = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
  16.  
  17.         if ($this->db->connect_errno > 0) {
  18.             die("Unable to connect to the database, throwing error: " . $db->connect_error);
  19.         }
  20.     }
  21.  
  22.     // performs a query, does a number of actions dependant on $type
  23.     public function query($sql, $type = false) {
  24.         $sql = $this->escape($sql);
  25.  
  26.         if ($result = $this->db->query($sql)) {
  27.             if ($type == false) {
  28.                 return $result;
  29.             } elseif ($type == true || "assoc") {
  30.                 if ($result->num_rows >= 2) {
  31.                     $array;
  32.                     $i = 1;
  33.  
  34.                     while ($row = $result->fetch_assoc()) {
  35.                         $array[$i] = $row;
  36.                         $i++;
  37.                     }
  38.  
  39.                     return $array;
  40.                 } elseif ($result->num_rows == 1) {
  41.                     return $result->fetch_assoc();
  42.                 }
  43.             } elseif ($type == "array") {
  44.                 if ($result->num_rows >= 2) {
  45.                     $array;
  46.                     $i = 1;
  47.  
  48.                     while ($row = $result->fetch_array()) {
  49.                         $array[$i] = $row;
  50.                         $i++;
  51.                     }
  52.  
  53.                     return $array;
  54.                 } elseif ($result->num_rows == 1) {
  55.                     return $result->fetch_array();
  56.                 }
  57.             }
  58.         } else {
  59.             die("There was an error running the query, throwing error: " . $this->db->error);
  60.         }
  61.     }
  62.  
  63.     // escapes a string before it is used in a query
  64.     private function escape($string) {
  65.         $string = $this->db->escape_string($string);
  66.         return $string;
  67.     }
  68.  
  69. }
  70.  
  71. $db = new database();
  72.  
  73. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement