Advertisement
Guest User

Untitled

a guest
Sep 16th, 2017
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 5.95 KB | None | 0 0
  1. class PDO_ext extends PDO {
  2.     // $statements: stores an array of prepared statements that have been used in order to reuse old ones
  3.     // Syntax: array(string(statement), object(mysqli_stmt), int(count))
  4.     private $statements = array();
  5.  
  6.     // $debug_mode will gather additional information about all queries performed
  7.     // This also allows you to display total queries and total SQL execution time
  8.     public $debug_mode = true;
  9.  
  10.     // $queries: stores an array of all queries and their execution times
  11.     // Requires $debug_mode to be on
  12.     // Syntax: array(string(statement), double(execution time))
  13.     private $queries = array();
  14.  
  15.  
  16.     public function query($query, $stmt_array = false) {
  17.  
  18.         // Get start time
  19.         if ($this->debug_mode == true) {
  20.             $this->queries[] = array($query,null);
  21.             $start = $this->getMicrotimeFloat();
  22.         }
  23.  
  24.         // Cache old prepared statements so that we don't need a new object every time
  25.         // This saves memory if executing the same statement over and over
  26.         $used_already = $this->get_used_statement($query);
  27.         if ($used_already !== false) {
  28.             $stmt = $used_already;
  29.         }
  30.         // Object doesn't exist so create a new one
  31.         else {
  32.             // Prepare the statement
  33.             try {
  34.                 $stmt = $this->prepare($query);
  35.             }
  36.             catch(PDOException $e) {
  37.                 $bt = debug_backtrace();
  38.                 echo 'Unable to prepare statement called from file <b>'.$bt[0]['file'].'</b> on line <b>'.$bt[0]['line'].'</b>:';
  39.                 echo '<br /><br />Mysql error: <i>'.$e->errorInfo[2].'</i>';
  40.                 exit();
  41.             }
  42.             $this->statements[] = array($query, $stmt, 1);
  43.             $stmt->setFetchMode(PDO::FETCH_ASSOC);
  44.         }
  45.  
  46.         // Bind the parameters if there are any
  47.         if (is_array($stmt_array)) {
  48.             foreach ($stmt_array as $vars) {
  49.                 if (isset($vars[2])) {
  50.                     switch($vars[2]) {
  51.                         case 'i':
  52.                             $type = PDO::PARAM_INT;
  53.                             break;
  54.                         case 's':
  55.                             $type = PDO::PARAM_STR;
  56.                             break;
  57.                         case 'b':
  58.                             $type = PDO::PARAM_BOOL;
  59.                             break;
  60.                         default:
  61.                             $type = $vars[2];
  62.                     }
  63.                 }
  64.                 else $type = false;
  65.                 $stmt->bindParam($vars[0],$vars[1],$type);
  66.             }
  67.         }
  68.        
  69.         // Execute the query
  70.         try {
  71.             set_error_handler(array($this, 'errorHandler')); // Set our own error handler to exit on warnings
  72.             $stmt->execute(); // Execute the query
  73.             restore_error_handler(); // Restore error handler on success
  74.         }
  75.         catch(PDOException $e) {
  76.             $bt = debug_backtrace();
  77.             echo 'Unable to execute query called from file <b>'.$bt[0]['file'].'</b> on line <b>'.$bt[0]['line'].'</b>';
  78.             echo '<br /><br />Mysql error: <i>';
  79.             echo $e->errorInfo[2];
  80.             echo '</i><br /><br />Debug info: <pre>';
  81.             $stmt->debugDumpParams();
  82.             // echo '<br /><br />Additional debug info:<br />'; print_r($bt);
  83.                 echo '</pre>';
  84.                 exit();
  85.         }
  86.  
  87.         // Get end time
  88.         if ($this->debug_mode == true) {
  89.             $end = $this->getMicrotimeFloat();
  90.             $this->queries[ count($this->queries)-1 ][ 1 ] = ($end - $start);
  91.         }
  92.  
  93.         // Get number of columns in the result set. If it is a SELECT, this will be greater than 0
  94.         $colcount = $stmt->columnCount();
  95.         if ($colcount > 0) {
  96.             $result = $stmt->fetchAll();
  97.         }
  98.         // It is a data manipulation query, so $colcount will be 0.
  99.         else $result = $stmt->rowCount();
  100.  
  101.         return $result;
  102.     }
  103.  
  104.     // Finds out if that statement has been used already to recycle it.
  105.     // This saves memory usage. For large numbers of queries,you can easily run out.
  106.     private function get_used_statement($query) {
  107.         foreach ($this->statements as $stmt) {
  108.             if ($query == $stmt[0]) {
  109.                 $stmt[2]++;
  110.                 return $stmt[1];
  111.             }
  112.         }
  113.         return false;
  114.     }
  115.    
  116.     private function errorHandler($errno, $errstr, $errfile, $errline) {
  117.         // This prints a 'warning' or a 'notice' error so that the script can exit
  118.         echo $errstr;
  119.     }
  120.  
  121.     // Used for getting the total execution time of the queries
  122.     private function getMicrotimeFloat () {
  123.         list ($msec, $sec) = explode(' ', microtime());
  124.         $microtime = (float)$msec + (float)$sec;
  125.         return $microtime;
  126.     }
  127.  
  128.     // Prints a history of the queries used along with their execution time
  129.     public function printDebugInfo() {
  130.         if ($this->debug_mode == false) {
  131.             echo '<br /><b>Warning</b>: Unable to call printDebugInfo() since $debug_mode is false.';
  132.             return false;
  133.         }
  134.         $totals = $this->getQueryTotals();
  135.  
  136.         if ($totals[0] == 0) {
  137.             echo '<br /><b>Notice</b>: printDebugInfo() was called, however no queries have been executed yet.';
  138.             return false;
  139.         }
  140.        
  141.         echo "<h3>Query history:</h3><ul>";
  142.         if ($totals[0] > 1) {
  143.             echo '<p>'.$totals[0].' queries. Total execution time for all queries: '.sprintf('%F12',$totals[1]).' sec.';
  144.         }
  145.         foreach ($this->queries as $query_arr) {
  146.             echo '<li>'.$query_arr[0].' (execution time: '.sprintf('%F12',$query_arr[1]).' sec)</li>';
  147.         }
  148.         echo "</ul>";
  149.     }
  150.  
  151.     public function getQueryTotals() {
  152.         $num_queries = count($this->queries);
  153.         $total_time = 0;
  154.         foreach ($this->queries as $query_arr) {
  155.             $total_time += $query_arr[1];
  156.         }
  157.         return array($num_queries,$total_time);
  158.     }
  159. }
  160.  
  161.  
  162. // Connect to database
  163. try {
  164.     switch ($driver) {
  165.         case 'postgre':
  166.             $pdo = new PDO_ext("pgsql:host=$host;dbname=$dbname;user=$user;password=$pass");
  167.             break;
  168.         case 'sqlite':
  169.             $pdo = new PDO_ext($sqlite_db);
  170.             break;
  171.         case 'mssql':
  172.             $pdo = new PDO_ext("mssql:host=$host;dbname=$dbname, $user, $pass");
  173.             break;
  174.         case 'sybase':
  175.             $pdo = new PDO_ext("sybase:host=$host;dbname=$dbname, $user, $pass");
  176.             break;
  177.         default:
  178.             $pdo = new PDO_ext("mysql:host=$host;dbname=$dbname", $user, $pass);
  179.     }
  180.     $pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
  181.    
  182. }
  183. catch(PDOException $e) {
  184.     die ("DB connection error ($driver): ".$e->getMessage());
  185. }
  186.  
  187.  
  188. // Example usage:
  189. $query = 'SELECT `username`,`id`,`email` FROM `users` WHERE username = :username AND `password` != :password';
  190. $vars = array(array(':username','myuser','s'),array(':password','12345','i'));
  191. $result = $pdo->query($query, $vars);
  192. $result2 = $pdo->query("SELECT * FROM users",'asdf');
  193. $pdo->printDebugInfo();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement