Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * This is the core function that you call in order to start a database instance
- */
- class DatabaseAdapterFactory
- {
- /**
- * Pass in the parameters like so: ("mysql", array("host" => "localhost", "user" => "user", "pass" => "pass", "name" => "db"))
- */
- public static function factory($type, $connInfo = NULL)
- {
- switch($type)
- {
- /**
- * MySQL instance
- */
- case 'mysql':
- $db = new MySQLAdapter($connInfo);
- break;
- }
- return($db);
- }
- }
- interface DatabaseAdapterInterface
- {
- public function __construct($connInfo = NULL);
- public function connect($connInfo);
- public function execute($query = NULL);
- public function fetcharray($resource = NULL);
- public function fetchassoc($resource = NULL);
- public function fetchobject($resource = NULL);
- public function fetchrow($resource = NULL);
- public function insertid();
- public function numrows($resource = NULL);
- public function result($resource = NULL, $row);
- public function close();
- public function error($text);
- public function setLogging($value);
- public function getLogging();
- public function appendToLog($query, $file, $line, $length, $status);
- public function retrieveLog();
- public function retrieveNumberOfQueries();
- public function setVerbose($value);
- public function getVerbose();
- public function setErrorMessage($error, $line, $file);
- public function printLog();
- public function __destruct();
- }
- abstract class DatabaseAdapterAbstract implements DatabaseAdapterInterface {}
- class MySQLAdapter extends DatabaseAdapterAbstract
- {
- /**
- * Used to symbolize whether a database connection has been made or not
- */
- private $connected;
- /**
- * Used to symbolise if Verbose mode is on or off.
- */
- private $verbose;
- /**
- * Used to store the connection to the database
- */
- private $connection;
- /**
- * Used to maintain a count of the number of SUCCESSFUL queries that were
- * executed.
- */
- private $queryCount;
- /**
- * Used to determine if we should be logging the queries that get executed.
- */
- private $logQueries;
- /**
- * Used to hold the log of all the queries that were executed along with how
- * long it took them to be executed.
- */
- private $log;
- /**
- * Used to hold a list of any exceptions that are thrown.
- */
- private $errorMessages;
- /**
- * Contains the path to the error log
- */
- private $MySQL_error_log;
- public function __construct($connInfo = NULL)
- {
- /* Turn off verbose mode so error messages won't show up */
- $this->setVerbose(FALSE);
- /* Initialize the number of queries executed */
- $this->queryCount = 0;
- /* Logging is set to TRUE | FALSE (on|off) */
- $this->setLogging(TRUE);
- /* Initialize the array for storing the logs as empty */
- $this->log = array();
- /* Initialize the array for store the error messages */
- $this->errorMessages = array();
- /* Set the path of the error_log */
- $this->MySQL_error_log = $_SERVER['DOCUMENT_ROOT'];
- /* Try to connect to the database */
- $this->connect($connInfo);
- }
- public function connect($connInfo)
- {
- /* Get database username and password information */
- $db_host = "localhost";
- $db_user = '';
- $db_pass = '';
- $db_name = "null";
- /* Check if they specified any of the information */
- if ($connInfo != NULL)
- {
- /* If they have let's see if there is any information */
- if (isset($connInfo['host']))
- {
- $db_host = $connInfo['host'];
- }
- if (isset($connInfo['user']))
- {
- $db_user = $connInfo['user'];
- }
- if (isset($connInfo['pass']))
- {
- $db_pass = $connInfo['pass'];
- }
- if (isset($connInfo['name']))
- {
- $db_name = $connInfo['name'];
- }
- }
- /* Assume we are connected */
- $this->connected = TRUE;
- /* Attempt to connect to the MySQL server */
- try
- {
- $this->connection = mysql_connect($db_host, $db_user, $db_pass);
- if($this->connection === FALSE)
- {
- /* Throw an exception as connection to the MySQL server has failed */
- throw new Exception('<strong>Error:</strong> Connection to Database Failed');
- }
- }
- catch (Exception $e)
- {
- $this->setErrorMessage($e->getMessage(), NULL, NULL);
- exit($this->error($e->getMessage()));
- }
- /* If there is an open MySQL connection */
- if($this->connection !== FALSE)
- {
- /* Attempt to select the database provided */
- try
- {
- if(mysql_select_db($db_name, $this->connection) === FALSE)
- {
- /* Throw an exception as selcting the database has failed */
- throw new Exception('<strong>Error:</strong> Cannot select Database');
- }
- }
- catch (Exception $e)
- {
- $this->setErrorMessage($e->getMessage(), NULL, NULL);
- exit($this->error($e->getMessage()));
- }
- }
- }
- /* This is the main Query function.
- * You are required to pass in a STRING containing MySQL syntax only.
- */
- public function execute($query = NULL)
- {
- /* Call the backtrace to get the calling function */
- $backTrace = debug_backtrace ();
- $callingLine = $backTrace[0]['line'];
- $callingFile = $backTrace[0]['file'];
- /* If there is no MySQL connection or Query passed, return NULL */
- if(($this->connected === FALSE) || ($query == NULL))
- {
- return(NULL);
- }
- $start = microtime(TRUE);
- try
- {
- /* Execute the database query */
- $queryExec = mysql_query($query);
- if($queryExec !== FALSE)
- {
- /* Add 1 to the query count */
- $this->queryCount += 1;
- }
- else
- {
- /* The query has failed somewhat for a reason */
- throw new Exception("Something appears to have gone wrong. If this problem persists, please contact us");
- }
- }
- catch(Exception $e)
- {
- $this->setErrorMessage(mysql_error(), $callingFile, $callingLine);
- if($this->getVerbose() === TRUE)
- {
- print($this->error(mysql_error()));
- }
- else
- {
- print($this->error($e->getMessage()));
- }
- $queryExec = NULL;
- }
- /* Calculate how long the query took */
- $length = microtime(TRUE) - $start;
- /* Check if we are logging all queries */
- if ($this->getLogging() === TRUE)
- {
- /* If we are then add it */
- $this->appendToLog($query, $callingFile, $callingLine, $length, ($queryExec) ? "success" : "failure");
- }
- return($queryExec);
- }
- /**
- * Returns an indexed & associative array with the results given from the query passed.
- */
- public function fetcharray($resource = NULL)
- {
- /* If there is no MySQL connection or MySQL Resource, return NULL */
- if(($this->connected === FALSE) || ($resource == NULL))
- {
- return(NULL);
- }
- return(@mysql_fetch_array($resource));
- }
- /**
- * Returns an associative array with the results given from the query passed.
- */
- public function fetchassoc($resource = NULL)
- {
- /* If there is no MySQL connection or MySQL Resource, return NULL */
- if(($this->connected === FALSE) || ($resource == NULL))
- {
- return(NULL);
- }
- return(@mysql_fetch_assoc($resource));
- }
- /**
- * Returns an object with the results given from the query passed.
- */
- public function fetchobject($resource = NULL)
- {
- /* If there is no MySQL connection or MySQL Resource, return NULL */
- if(($this->connected === FALSE) || ($resource == NULL))
- {
- return(NULL);
- }
- return(@mysql_fetch_object($resource));
- }
- /**
- * Returns an full row from the query passed.
- */
- public function fetchrow($resource = NULL)
- {
- /* If there is no MySQL connection or MySQL Resource, return NULL */
- if(($this->connected === FALSE) || ($resource == NULL))
- {
- return(NULL);
- }
- return(@mysql_fetch_row($resource));
- }
- /**
- * Returns the last insert ID from an auto_increment column.
- */
- public function insertid()
- {
- /* If there is no MySQL connection, return NULL */
- if(($this->connected === FALSE))
- {
- return(NULL);
- }
- return(@mysql_insert_id($resource));
- }
- /**
- * Returns an total number of rows of the results given from the query passed.
- */
- public function numrows($resource = NULL)
- {
- /* If there is no MySQL connection or MySQL Resource, return NULL */
- if(($this->connected === FALSE) || ($resource == NULL))
- {
- return(NULL);
- }
- return(@mysql_num_rows($resource));
- }
- /**
- * Returns an total number of rows of the results given from the query passed.
- */
- public function result($resource = NULL, $row)
- {
- /* If there is no MySQL connection or MySQL Resource, return NULL */
- if(($this->connected === FALSE) || ($resource == NULL) || !ctype_digit($row))
- {
- return(NULL);
- }
- return(@mysql_result($resource, $row));
- }
- /**
- * Close the current MySQL connection
- */
- public function close()
- {
- if(($this->connected === TRUE))
- {
- mysql_close($this->connection);
- }
- }
- /**
- * This function is used in order to display an error message about what went wrong within the query.
- */
- public function error($text)
- {
- return("<br /><font color='red'><b>ERROR</b></font> - $text<br />");
- }
- /**
- * This function is used in order to turn on/off the query logging functionality.
- */
- public function setLogging($value)
- {
- if($value === TRUE || $value === FALSE)
- {
- $this->logQueries = $value;
- }
- }
- /**
- * This function is used in order to determine if we are keeping logs of all of the queries that occur.
- */
- public function getLogging()
- {
- return($this->logQueries);
- }
- /**
- * This function is used in order to add the query to the list of all queries which were executed.
- */
- public function appendToLog($query, $file, $line, $length, $status)
- {
- $this->log[] = array("query" => $query, "file" => $file, "line" => $line, "time" => $length, "status" => $status);
- }
- /**
- * This function is used in order to retrieve the raw version of the log (the array that actually holds the log).
- */
- public function retrieveLog()
- {
- return($this->log);
- }
- /**
- * This function will return the number of queries that were successfully executed
- */
- public function retrieveNumberOfQueries()
- {
- return($this->queryCount);
- }
- /**
- * This function is used in order to set whether or not verbose mode is on or off.
- */
- public function setVerbose($value)
- {
- if($value === TRUE || $value === FALSE)
- {
- $this->verbose = $value;
- }
- }
- /**
- * This function is used in order to determine if Verbose mode is turned on or not.
- */
- public function getVerbose()
- {
- return($this->verbose);
- }
- /**
- * This function is used to set the error message for the specified error.
- */
- public function setErrorMessage($error, $file, $line)
- {
- $errorId = md5(serialize($error));
- $this->errorMessages[$errorId] = array("error" => $error, "file" => $file, "line" => $line);
- }
- /**
- * This function is used in order to display the log in a more useful manner.
- * This function will output the information directly onto the page.
- */
- public function printLog()
- {
- echo ("<table style='width: 75%; border: 1px solid black; border-collapse: collapse; margin: 0 auto;'>" . PHP_EOL);
- echo ("\t<tr>" . PHP_EOL);
- echo ("\t\t<th style='border: 1px solid black; padding: 5px;'>Query</th>" . PHP_EOL);
- echo ("\t\t<th style='border: 1px solid black; padding: 5px;'>File</th>" . PHP_EOL);
- echo ("\t\t<th style='border: 1px solid black; padding: 5px;'>Line</th>" . PHP_EOL);
- echo ("\t\t<th style='border: 1px solid black; padding: 5px;'>Time (seconds)</th>" . PHP_EOL);
- echo ("\t\t<th style='border: 1px solid black; padding: 5px;'>Status</th>" . PHP_EOL);
- echo ("\t</tr>" . PHP_EOL);
- foreach ($this->retrieveLog() as $entry)
- {
- $totalTime += $entry['time'];
- echo ("\t<tr>" . PHP_EOL);
- echo ("\t\t<td style = 'border: 1px solid black; padding: 5px;'>" . $entry['query'] . "</td>" . PHP_EOL);
- echo ("\t\t<td style = 'border: 1px solid black; padding: 5px;'>" . $entry['file'] . "</td>" . PHP_EOL);
- echo ("\t\t<td style = 'border: 1px solid black; padding: 5px;'>" . $entry['line'] . "</td>" . PHP_EOL);
- echo ("\t\t<td style = 'border: 1px solid black; padding: 5px;'>" . $entry['time'] . "</td>" . PHP_EOL);
- echo ("\t\t<td style = 'border: 1px solid black; padding: 5px;'>" . $entry['status'] . "</td>" . PHP_EOL);
- echo ("\t</tr>" . PHP_EOL);
- }
- echo ("</table>" . PHP_EOL);
- echo ("<center><strong>Total Time</strong><br />$totalTime</center>" . PHP_EOL);
- }
- /**
- * Put any errors into an error log. If one does not exist, create it.
- */
- public function __destruct()
- {
- if(count($this->errorMessages) > 0)
- {
- $logFile = dirname(__FILE__) . '/mysql_error_log';
- if(file_exists($logFile) === FALSE)
- {
- $createLog = fopen($logFile, 'w');
- fclose($createLog);
- }
- $fileContents = file_get_contents($logFile);
- $errors = '';
- foreach($this->errorMessages as $k => $data)
- {
- $errors .= 'Error in ' . $data['file'] . ' on line ' . $data['line'] . "\n" . 'Error Reads: ' . $data['error'] . "\n" . '----------------------------------------------------' . "\n";
- }
- file_put_contents($logFile, $fileContents . $errors, LOCK_EX);
- }
- }
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement