Advertisement
Guest User

Untitled

a guest
Aug 15th, 2017
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 13.23 KB | None | 0 0
  1. /**
  2.  * This is the core function that you call in order to start a database instance
  3.  */
  4. class DatabaseAdapterFactory
  5. {
  6.     /**
  7.      * Pass in the parameters like so: ("mysql", array("host" => "localhost", "user" => "user", "pass" => "pass", "name" => "db"))
  8.      */
  9.     public static function factory($type, $connInfo = NULL)
  10.     {
  11.         switch($type)
  12.         {
  13.             /**
  14.              * MySQL instance
  15.              */
  16.             case 'mysql':
  17.                 $db =  new MySQLAdapter($connInfo);
  18.                 break;
  19.         }
  20.        
  21.         return($db);
  22.     }
  23. }
  24.  
  25. interface DatabaseAdapterInterface
  26. {
  27.     public function __construct($connInfo = NULL);
  28.     public function connect($connInfo);
  29.     public function execute($query = NULL);
  30.     public function fetcharray($resource = NULL);
  31.     public function fetchassoc($resource = NULL);
  32.     public function fetchobject($resource = NULL);
  33.     public function fetchrow($resource = NULL);
  34.     public function insertid();
  35.     public function numrows($resource = NULL);
  36.     public function result($resource = NULL, $row);
  37.     public function close();
  38.     public function error($text);
  39.     public function setLogging($value);
  40.     public function getLogging();
  41.     public function appendToLog($query, $file, $line, $length, $status);
  42.     public function retrieveLog();
  43.     public function retrieveNumberOfQueries();
  44.     public function setVerbose($value);
  45.     public function getVerbose();
  46.     public function setErrorMessage($error, $line, $file);
  47.     public function printLog();
  48.     public function __destruct();
  49. }
  50.  
  51. abstract class DatabaseAdapterAbstract implements DatabaseAdapterInterface {}
  52.  
  53. class MySQLAdapter extends DatabaseAdapterAbstract
  54. {
  55.     /**
  56.      * Used to symbolize whether a database connection has been made or not
  57.      */
  58.     private $connected;
  59.     /**
  60.      * Used to symbolise if Verbose mode is on or off.
  61.      */
  62.     private $verbose;
  63.     /**
  64.      * Used to store the connection to the database
  65.      */
  66.     private $connection;
  67.     /**
  68.      * Used to maintain a count of the number of SUCCESSFUL queries that were
  69.      * executed.
  70.      */
  71.     private $queryCount;
  72.     /**
  73.      * Used to determine if we should be logging the queries that get executed.
  74.      */
  75.     private $logQueries;        
  76.     /**
  77.      * Used to hold the log of all the queries that were executed along with how
  78.      * long it took them to be executed.
  79.      */
  80.     private $log;
  81.     /**
  82.      * Used to hold a list of any exceptions that are thrown.
  83.      */
  84.     private $errorMessages;
  85.     /**
  86.      * Contains the path to the error log
  87.      */
  88.     private $MySQL_error_log;
  89.    
  90.     public function __construct($connInfo = NULL)
  91.     {    
  92.                
  93.         /* Turn off verbose mode so error messages won't show up */
  94.         $this->setVerbose(FALSE);
  95.                
  96.         /* Initialize the number of queries executed */
  97.         $this->queryCount = 0;
  98.        
  99.         /* Logging is set to TRUE | FALSE (on|off) */
  100.         $this->setLogging(TRUE);
  101.        
  102.         /* Initialize the array for storing the logs as empty */
  103.         $this->log = array();
  104.        
  105.         /* Initialize the array for store the error messages */
  106.         $this->errorMessages = array();
  107.        
  108.         /* Set the path of the error_log */
  109.         $this->MySQL_error_log = $_SERVER['DOCUMENT_ROOT'];
  110.                
  111.         /* Try to connect to the database */
  112.         $this->connect($connInfo);
  113.     }
  114.    
  115.     public function connect($connInfo)
  116.     {  
  117.         /* Get database username and password information */
  118.         $db_host = "localhost";
  119.         $db_user = '';
  120.         $db_pass = '';
  121.         $db_name = "null";
  122.                
  123.         /* Check if they specified any of the information */
  124.         if ($connInfo != NULL)
  125.         {
  126.             /* If they have let's see if there is any information */        
  127.             if (isset($connInfo['host']))
  128.             {
  129.                 $db_host = $connInfo['host'];
  130.             }
  131.             if (isset($connInfo['user']))
  132.             {
  133.                 $db_user = $connInfo['user'];
  134.             }
  135.             if (isset($connInfo['pass']))
  136.             {
  137.                 $db_pass = $connInfo['pass'];
  138.             }
  139.             if (isset($connInfo['name']))
  140.             {
  141.                 $db_name = $connInfo['name'];
  142.             }
  143.         }
  144.        
  145.         /* Assume we are connected */
  146.         $this->connected = TRUE;
  147.        
  148.         /* Attempt to connect to the MySQL server */
  149.         try
  150.         {
  151.             $this->connection = mysql_connect($db_host, $db_user, $db_pass);
  152.            
  153.             if($this->connection === FALSE)
  154.             {
  155.                 /* Throw an exception as connection to the MySQL server has failed */
  156.                 throw new Exception('<strong>Error:</strong> Connection to Database Failed');
  157.             }
  158.         }
  159.         catch (Exception $e)
  160.         {
  161.             $this->setErrorMessage($e->getMessage(), NULL, NULL);
  162.            
  163.             exit($this->error($e->getMessage()));
  164.         }
  165.        
  166.        
  167.         /* If there is an open MySQL connection */
  168.         if($this->connection !== FALSE)
  169.         {
  170.             /* Attempt to select the database provided */
  171.             try
  172.             {
  173.                 if(mysql_select_db($db_name, $this->connection) === FALSE)
  174.                 {
  175.                     /* Throw an exception as selcting the database has failed */
  176.                     throw new Exception('<strong>Error:</strong> Cannot select Database');
  177.                 }
  178.             }
  179.             catch (Exception $e)
  180.             {
  181.                 $this->setErrorMessage($e->getMessage(), NULL, NULL);
  182.                
  183.                 exit($this->error($e->getMessage()));  
  184.             }
  185.         }
  186.     }
  187.    
  188.     /* This is the main Query function.
  189.      * You are required to pass in a STRING containing MySQL syntax only.
  190.      */
  191.     public function execute($query = NULL)
  192.     {
  193.         /* Call the backtrace to get the calling function */
  194.         $backTrace = debug_backtrace ();
  195.         $callingLine = $backTrace[0]['line'];
  196.         $callingFile = $backTrace[0]['file'];
  197.        
  198.         /* If there is no MySQL connection or Query passed, return NULL */
  199.         if(($this->connected === FALSE) || ($query == NULL))
  200.         {
  201.             return(NULL);
  202.         }
  203.  
  204.         $start = microtime(TRUE);
  205.  
  206.         try
  207.         {          
  208.             /* Execute the database query */
  209.             $queryExec = mysql_query($query);
  210.            
  211.             if($queryExec !== FALSE)
  212.             {  
  213.                 /* Add 1 to the query count */
  214.                 $this->queryCount += 1;
  215.             }
  216.             else
  217.             {
  218.                 /* The query has failed somewhat for a reason */
  219.                 throw new Exception("Something appears to have gone wrong. If this problem persists, please contact us");
  220.             }
  221.         }
  222.         catch(Exception $e)
  223.         {
  224.             $this->setErrorMessage(mysql_error(), $callingFile, $callingLine);
  225.            
  226.             if($this->getVerbose() === TRUE)
  227.             {
  228.                 print($this->error(mysql_error()));
  229.             }
  230.             else
  231.             {
  232.                 print($this->error($e->getMessage()));
  233.             }
  234.            
  235.             $queryExec = NULL;
  236.         }
  237.        
  238.         /* Calculate how long the query took */
  239.         $length = microtime(TRUE) - $start;
  240.        
  241.         /* Check if we are logging all queries */
  242.         if ($this->getLogging() === TRUE)
  243.         {
  244.             /* If we are then add it */
  245.             $this->appendToLog($query, $callingFile, $callingLine, $length, ($queryExec) ? "success" : "failure");
  246.         }
  247.        
  248.         return($queryExec);
  249.     }
  250.    
  251.     /**
  252.      * Returns an indexed & associative array with the results given from the query passed.
  253.      */
  254.     public function fetcharray($resource = NULL)
  255.     {
  256.         /* If there is no MySQL connection or MySQL Resource, return NULL */
  257.         if(($this->connected === FALSE) || ($resource == NULL))
  258.         {
  259.             return(NULL);
  260.         }
  261.        
  262.         return(@mysql_fetch_array($resource));
  263.     }
  264.    
  265.     /**
  266.      * Returns an associative array with the results given from the query passed.
  267.      */
  268.     public function fetchassoc($resource = NULL)
  269.     {
  270.         /* If there is no MySQL connection or MySQL Resource, return NULL */
  271.         if(($this->connected === FALSE) || ($resource == NULL))
  272.         {
  273.             return(NULL);
  274.         }
  275.        
  276.         return(@mysql_fetch_assoc($resource));
  277.     }
  278.    
  279.     /**
  280.      * Returns an object with the results given from the query passed.
  281.      */
  282.     public function fetchobject($resource = NULL)
  283.     {
  284.         /* If there is no MySQL connection or MySQL Resource, return NULL */
  285.         if(($this->connected === FALSE) || ($resource == NULL))
  286.         {
  287.             return(NULL);
  288.         }
  289.        
  290.         return(@mysql_fetch_object($resource));
  291.     }
  292.    
  293.     /**
  294.      * Returns an full row from the query passed.
  295.      */
  296.     public function fetchrow($resource = NULL)
  297.     {
  298.         /* If there is no MySQL connection or MySQL Resource, return NULL */
  299.         if(($this->connected === FALSE) || ($resource == NULL))
  300.         {
  301.             return(NULL);
  302.         }
  303.        
  304.         return(@mysql_fetch_row($resource));
  305.     }
  306.    
  307.     /**
  308.      * Returns the last insert ID from an auto_increment column.
  309.      */
  310.     public function insertid()
  311.     {
  312.         /* If there is no MySQL connection, return NULL */
  313.         if(($this->connected === FALSE))
  314.         {
  315.             return(NULL);
  316.         }
  317.        
  318.         return(@mysql_insert_id($resource));
  319.     }
  320.    
  321.     /**
  322.      * Returns an total number of rows of the results given from the query passed.
  323.      */
  324.     public function numrows($resource = NULL)
  325.     {
  326.         /* If there is no MySQL connection or MySQL Resource, return NULL */
  327.         if(($this->connected === FALSE) || ($resource == NULL))
  328.         {
  329.             return(NULL);
  330.         }
  331.        
  332.         return(@mysql_num_rows($resource));
  333.     }
  334.    
  335.     /**
  336.      * Returns an total number of rows of the results given from the query passed.
  337.      */
  338.     public function result($resource = NULL, $row)
  339.     {
  340.         /* If there is no MySQL connection or MySQL Resource, return NULL */
  341.         if(($this->connected === FALSE) || ($resource == NULL) || !ctype_digit($row))
  342.         {
  343.             return(NULL);
  344.         }
  345.        
  346.         return(@mysql_result($resource, $row));
  347.     }
  348.    
  349.     /**
  350.      * Close the current MySQL connection
  351.      */
  352.     public function close()
  353.     {
  354.         if(($this->connected === TRUE))
  355.         {
  356.             mysql_close($this->connection);
  357.         }
  358.     }
  359.    
  360.     /**
  361.      * This function is used in order to display an error message about what went wrong within the query.
  362.      */
  363.     public function error($text)
  364.     {
  365.         return("<br /><font color='red'><b>ERROR</b></font> - $text<br />");
  366.     }
  367.    
  368.     /**
  369.      * This function is used in order to turn on/off the query logging functionality.
  370.      */
  371.     public function setLogging($value)
  372.     {
  373.         if($value === TRUE || $value === FALSE)
  374.         {
  375.             $this->logQueries = $value;
  376.         }
  377.     }
  378.    
  379.     /**
  380.      * This function is used in order to determine if we are keeping logs of all of the queries that occur.
  381.      */
  382.     public function getLogging()
  383.     {
  384.         return($this->logQueries);
  385.     }
  386.    
  387.     /**
  388.      * This function is used in order to add the query to the list of all queries which were executed.
  389.      */
  390.     public function appendToLog($query, $file, $line, $length, $status)
  391.     {
  392.         $this->log[] = array("query" => $query, "file" => $file, "line" => $line, "time" => $length, "status" => $status);
  393.     }
  394.    
  395.     /**
  396.      * This function is used in order to retrieve the raw version of the log (the array that actually holds the log).
  397.      */
  398.     public function retrieveLog()
  399.     {
  400.         return($this->log);
  401.     }
  402.    
  403.     /**
  404.      * This function will return the number of queries that were successfully executed
  405.      */
  406.     public function retrieveNumberOfQueries()
  407.     {
  408.         return($this->queryCount);
  409.     }
  410.    
  411.     /**
  412.      * This function is used in order to set whether or not verbose mode is on or off.
  413.      */
  414.     public function setVerbose($value)
  415.     {
  416.         if($value === TRUE || $value === FALSE)
  417.         {
  418.             $this->verbose = $value;
  419.         }
  420.     }
  421.     /**
  422.      * This function is used in order to determine if Verbose mode is turned on or not.
  423.      */
  424.     public function getVerbose()
  425.     {
  426.         return($this->verbose);
  427.     }
  428.    
  429.     /**
  430.      * This function is used to set the error message for the specified error.
  431.      */
  432.     public function setErrorMessage($error, $file, $line)
  433.     {
  434.         $errorId = md5(serialize($error));
  435.    
  436.         $this->errorMessages[$errorId] = array("error" => $error, "file" => $file, "line" => $line);
  437.     }
  438.    
  439.     /**
  440.      * This function is used in order to display the log in a more useful manner.
  441.      * This function will output the information directly onto the page.
  442.      */
  443.     public function printLog()
  444.     {
  445.         echo ("<table style='width: 75%; border: 1px solid black; border-collapse: collapse; margin: 0 auto;'>" . PHP_EOL);
  446.         echo ("\t<tr>" . PHP_EOL);
  447.         echo ("\t\t<th style='border: 1px solid black; padding: 5px;'>Query</th>" . PHP_EOL);
  448.         echo ("\t\t<th style='border: 1px solid black; padding: 5px;'>File</th>" . PHP_EOL);
  449.         echo ("\t\t<th style='border: 1px solid black; padding: 5px;'>Line</th>" . PHP_EOL);
  450.         echo ("\t\t<th style='border: 1px solid black; padding: 5px;'>Time (seconds)</th>" . PHP_EOL);
  451.         echo ("\t\t<th style='border: 1px solid black; padding: 5px;'>Status</th>" . PHP_EOL);
  452.         echo ("\t</tr>" . PHP_EOL);
  453.        
  454.         foreach ($this->retrieveLog() as $entry)
  455.         {
  456.             $totalTime += $entry['time'];
  457.            
  458.             echo ("\t<tr>" . PHP_EOL);
  459.            
  460.             echo ("\t\t<td style = 'border: 1px solid black; padding: 5px;'>" . $entry['query'] . "</td>" . PHP_EOL);
  461.            
  462.             echo ("\t\t<td style = 'border: 1px solid black; padding: 5px;'>" . $entry['file'] . "</td>" . PHP_EOL);
  463.            
  464.             echo ("\t\t<td style = 'border: 1px solid black; padding: 5px;'>" . $entry['line'] . "</td>" . PHP_EOL);
  465.            
  466.             echo ("\t\t<td style = 'border: 1px solid black; padding: 5px;'>" . $entry['time'] . "</td>" . PHP_EOL);
  467.            
  468.             echo ("\t\t<td style = 'border: 1px solid black; padding: 5px;'>" . $entry['status'] . "</td>" . PHP_EOL);
  469.            
  470.             echo ("\t</tr>" . PHP_EOL);
  471.         }
  472.        
  473.         echo ("</table>" . PHP_EOL);
  474.  
  475.         echo ("<center><strong>Total Time</strong><br />$totalTime</center>" . PHP_EOL);
  476.     }
  477.    
  478.     /**
  479.      * Put any errors into an error log. If one does not exist, create it.
  480.      */
  481.     public function __destruct()
  482.     {
  483.         if(count($this->errorMessages) > 0)
  484.         {
  485.             $logFile = dirname(__FILE__) . '/mysql_error_log';
  486.            
  487.             if(file_exists($logFile) === FALSE)
  488.             {
  489.                 $createLog = fopen($logFile, 'w');
  490.                 fclose($createLog);
  491.             }
  492.            
  493.             $fileContents = file_get_contents($logFile);
  494.            
  495.             $errors = '';
  496.            
  497.             foreach($this->errorMessages as $k => $data)
  498.             {
  499.                 $errors .=  'Error in ' . $data['file'] . ' on line ' . $data['line'] . "\n" . 'Error Reads: ' . $data['error'] . "\n" . '----------------------------------------------------' . "\n";
  500.             }
  501.            
  502.             file_put_contents($logFile, $fileContents . $errors, LOCK_EX);
  503.         }
  504.     }
  505. }
  506. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement