MySQL Database Class
This is a set of classes which make communicating with a MySQL Database a lot easier.
It's divided into four classes:
- MySQLDatabase, the main class, which connects to your MySQL server and selects the database etc.
- MySQLResult, when you execute a query which returns rows, this object will be returned. From this object, you can fetch rows, and a lot more. This class also implements the Iterator interface, so you can use this class in a foreach statement.
- MySQLStatement, a class which can be used for parameter binding, repetitive mysql queries etc.
- MySQLException, an exception class, which will be thrown when an error occurs.
You can connect to multiple servers, and select multiple databases, also transactions are supported, but transactions only work with InnoDB as engine.
Download script as zip
Tags:
OOP
MySQL
PHP
It's divided into four classes:
- MySQLDatabase, the main class, which connects to your MySQL server and selects the database etc.
- MySQLResult, when you execute a query which returns rows, this object will be returned. From this object, you can fetch rows, and a lot more. This class also implements the Iterator interface, so you can use this class in a foreach statement.
- MySQLStatement, a class which can be used for parameter binding, repetitive mysql queries etc.
- MySQLException, an exception class, which will be thrown when an error occurs.
You can connect to multiple servers, and select multiple databases, also transactions are supported, but transactions only work with InnoDB as engine.
Download script as zip
Source
- MySQLDatabase.php
- MySQLResult.php
- MySQLStatement.php
- MySQLException.php
- example.php
- <?php
- /**
- * MySQL Class
- * @package Database
- * @author Lucas van Dijk (http://www.return1.net)
- * @copyright (c) Copyright 2007 by Lucas van Dijk
- * @license http://www.opensource.org/licenses/gpl-license.php
- */
- /**
- * MySQL Database class
- *
- * Example:
- * <code>
- * $db = new MySQL($host, $user, $pass, $database);
- * $result = $db -> query("SELECT * FROM table LIMIT 1");
- * $row = $result -> fetch();
- * </code>
- * @package Database
- * @author Lucas van Dijk
- */
- class MySQLDatabase
- {
- protected $connection;
- protected $in_transaction;
- /**
- * Constructor, connects to the database, and selects the database
- * @param string $host The IP of the database server
- * @param string $database The database name to select
- * @param string $user The username of the database
- * @param string $pass the password of the database
- */
- public function __construct($host = '', $database = '', $user = '', $pass = '')
- {
- // Connect to database
- {
- $this -> connect($host, $user, $pass);
- }
- // Select database
- {
- $this -> select_database($database);
- }
- $this -> in_transaction = false;
- }
- /**
- * Destructor, closes the connection to the database
- */
- public function __destruct()
- {
- }
- /**
- * Connect to the database
- * @param string $host The server where MySQL is
- * @param string $user The username of the MySQL server
- * @param string $pass The password of the MySQL server
- */
- public function connect($host, $user, $pass = '')
- {
- if(!$this -> connection)
- {
- throw new MySQLException('Could not connect to MySQL Server');
- }
- }
- /**
- * Selects another database
- * @param string $database_name The name of the database
- */
- public function select_database($database_name)
- {
- {
- throw new MySQLException('Could not select database');
- }
- }
- /**
- * Executes a query which returns rows (SELECT statements etc.), and returns a MySQLResult object
- * @param string|MySQLStatement $query The query to execute
- * @return MySQLResult A MySQLResult object containing the query result
- */
- public function query($query)
- {
- if($query instanceof MySQLStatement)
- {
- $query = $query->__toString();
- }
- {
- if($this -> in_transaction)
- {
- $this -> rollback();
- $this -> in_transaction = false;
- }
- throw new MySQLException('Could not execute query', $query);
- }
- self::$num_queries++;
- return new MySQLResult($result);
- }
- /**
- * Executes a query which doesn't return rows (UPDATE statement etc.), and returns the number of rows affected
- * @param string $query The query to execute
- * @return int The number of rows affected
- */
- public function execute($query)
- {
- if($query instanceof MySQLStatement)
- {
- $query = $query->__toString();
- }
- {
- if($this -> in_transaction)
- {
- $this -> rollback();
- $this -> in_transaction = false;
- }
- throw new MySQLException('Could not execute query', $query);
- }
- self::$num_queries++;
- }
- /**
- * Starts a transaction
- */
- public function begin_transaction()
- {
- if(!$this -> in_transaction)
- {
- {
- throw new MySQLException('Could not start transaction');
- }
- $this -> in_transaction = true;
- }
- else
- {
- throw new MySQLException('Already in transaction, call MySQL::end_transaction() first');
- }
- }
- /**
- * Ends a transaction, and commits the queries
- */
- public function end_transaction()
- {
- if($this -> in_transaction)
- {
- $this -> in_transaction = false;
- {
- $this -> rollback();
- throw new MySQLException('Could not end transaction');
- }
- }
- else
- {
- throw new MySQLException('Not in a transaction');
- }
- }
- /**
- * Rolls the transaction back
- */
- public function rollback()
- {
- {
- throw new MySQLException('Could not rollback');
- }
- }
- /**
- * Prepares an MySQL query
- * @param string $query The query to prepare
- * @return MySQLStatement A MySQLStatement object
- */
- public function prepare($query)
- {
- return new MySQLStatement($query, $this -> connection);
- }
- /**
- * Returns the last ID from the last INSERT statement
- * @return int
- */
- public function last_id()
- {
- }
- /**
- * Gets the number of queries executes
- * @return int The number of queries
- */
- public function get_num_queries()
- {
- return self::$num_queries;
- }
- /**
- * Escapes the given text
- * @return string The escaped text
- */
- public function escape($text)
- {
- }
- }
- <?php
- /**
- * MySQL Class
- * @package Database
- * @author Lucas van Dijk (http://www.return1.net)
- * @copyright (c) Copyright 2007 by Lucas van Dijk
- * @license http://www.opensource.org/licenses/gpl-license.php
- */
- /**
- * The MySQL Result class
- *
- * Holds the result of an MySQL Query
- * Example:
- * <code>
- * $result = $db -> query("SELECT * FROM table");
- * echo "Num Rows: ".$result -> num_rows()."<br />";
- * foreach($result as $row)
- * {
- * echo $row['title']."<br />";
- * }
- * </code>
- * @package Database
- * @author Lucas van Dijk
- */
- class MySQLResult implements Iterator
- {
- protected $query_result;
- protected $last_row;
- protected $rowset;
- protected $pointer;
- /**
- * Inits our $query_result var
- * @param resource $result a valid resource from mysql_query()
- */
- public function __construct(&$result)
- {
- {
- throw new MySQLException('$result is not a valid resource');
- }
- $this -> query_result = $result;
- }
- public function __destruct()
- {
- }
- /**
- * Fetches a row
- * @return array|bool Returns an array with the current row, or false if there aren't any rows left
- */
- public function fetch()
- {
- return $this -> last_row;
- }
- /**
- * Fetches all rows, and gives an array back
- * @return array A multi dimensional array containing all rows
- */
- public function fetch_rowset()
- {
- {
- return $this -> rowset;
- }
- else
- {
- while($row = $this -> fetch())
- {
- $result[] = $row;
- }
- $this -> rowset = $result;
- return $result;
- }
- }
- /**
- * Fetches the value of an certain field
- * @param string $field The name of the field to fetch
- * @param int $rownr The number of the row, if you enter -1, the last row fetched will be used
- * @return string The value of the field
- */
- public function fetch_field($field, $rownr = -1)
- {
- $result = false;
- if($rownr > -1)
- {
- }
- else
- {
- {
- $result = $this -> last_row[$field];
- }
- else
- {
- $this -> fetch();
- $result = $this -> last_row[$field];
- }
- }
- return $result;
- }
- /**
- * Gets the number of rows
- * @return int The number of rows
- */
- public function num_rows()
- {
- }
- /**
- * Changes the row pointer
- * @param int $row The row number
- */
- public function row_seek($row)
- {
- {
- throw new MySQLException('Row not found');
- }
- $this -> pointer = $row;
- }
- //
- // Iteration functions
- //
- /**
- * Rewinds the current place
- */
- {
- if($this -> num_rows() > 0)
- {
- $this -> row_seek(0);
- }
- }
- /**
- * Returns the current row
- */
- {
- {
- $this -> fetch();
- }
- return $this -> last_row;
- }
- /**
- * Goes to the next row
- */
- {
- $this -> fetch();
- }
- /**
- * Goes to the previous row
- */
- public function previous()
- {
- $this -> row_seek($this -> pointer - 1);
- }
- /**
- * Checks of we're on the end of the list
- */
- public function valid()
- {
- }
- /**
- * Returns the current pointer
- */
- {
- return $this -> pointer;
- }
- }
- <?php
- /**
- * MySQL Class
- * @package Database
- * @author Lucas van Dijk (http://www.return1.net)
- * @copyright (c) Copyright 2007 by Lucas van Dijk
- * @license http://www.opensource.org/licenses/gpl-license.php
- */
- /**
- * MySQL Statement class, used for parameter binding, and to simplify queries you must often execute
- *
- * Example:
- * <code>
- * try
- * {
- * $db -> select_database('test');
- * $statement = $db->prepare("INSERT INTO test.persons (name, age) VALUES (?, ?)");
- * $statement -> bind_parameter(0, "Lucas van Dijk");
- * $statement -> bind_parameter(1, 16);
- *
- * $db -> execute($statement);
- *
- * // Set new value
- * $statement -> bind_parameter(0, "Ted's");
- * $statement -> bind_parameter(1, 19);
- *
- * $db -> execute($statement);
- * }
- * catch(MySQLException $e)
- * {
- * die($e->getMessage().": ".$e->get_error());
- * }
- * </code>
- * @package Database
- * @author Lucas van Dijk
- */
- class MySQLStatement
- {
- protected $query;
- protected $parameters;
- protected $parameters2;
- /**
- * Constructor, sets the query
- * @param string $query The query
- */
- public function __construct($query)
- {
- $this -> query = $query;
- }
- /**
- * Binds a placeholder to the query
- * @param string|array $key the key of the placeholder or an array with placeholders
- * @param mixed $value the value of the placeholder
- */
- public function bind_parameter($key, $value = '')
- {
- {
- foreach($key as $place_holder => $value)
- {
- {
- $this -> parameters2[] = ctype_digit((string) $value) ? $value : "'".mysql_real_escape_string($value)."'";
- }
- else
- {
- $this -> parameters[$place_holder] = ctype_digit((string) $value) ? $value : "'".mysql_real_escape_string($value)."'";
- }
- }
- }
- {
- throw new Exception('First parameter is not an array.');
- }
- else
- {
- {
- $this -> parameters2[$key] = ctype_digit((string) $value) ? $value : "'".mysql_real_escape_string($value)."'";
- }
- else
- {
- $this -> parameters[$key] = ctype_digit((string) $value) ? $value : "'".mysql_real_escape_string($value)."'";
- }
- }
- }
- /**
- * Loops through the complete string, and replaces all parameters
- * @return string The query with the replaced parameters
- */
- protected function replace_parameters()
- {
- $query = $this -> query;
- {
- }
- {
- $num_params = 0;
- {
- if($query{$i} == '?')
- {
- {
- $num_params++;
- }
- }
- }
- }
- return $query;
- }
- /**
- * Simply outputs the query
- * @return string The query
- */
- public function __toString()
- {
- return $this -> replace_parameters();
- }
- }
- <?php
- /**
- * MySQL Class
- * @package Database
- * @author Lucas van Dijk (http://www.return1.net)
- * @copyright (c) Copyright 2007 by Lucas van Dijk
- * @license http://www.opensource.org/licenses/gpl-license.php
- */
- /**
- * MySQL Exception class
- *
- * Retreives the last error, and err no. for debugging
- * @package Database
- * @author Lucas van Dijk
- */
- class MySQLException extends Exception
- {
- protected $error;
- protected $sql_query;
- public function __construct($message, $sql_query = '')
- {
- // Retreive the last error from MySQL
- $this -> message = $message;
- $this -> sql_query = $sql_query;
- parent::__construct();
- }
- public function get_error()
- {
- return $this -> error;
- }
- public function get_sql_query()
- {
- return $this -> sql_query;
- }
- public function __toString()
- {
- return "[#".$this -> code."] ".$this -> message.": ".$this -> error."<br /><br /><strong>StackTrace</strong>".$this -> getTraceAsString();
- }
- }
- <?php
- /**
- * MySQL Class
- * @package Database
- * @author Lucas van Dijk (http://www.return1.net)
- * @copyright (c) Copyright 2007 by Lucas van Dijk
- * @license http://www.opensource.org/licenses/gpl-license.php
- */
- include 'MySQLDatabase.php';
- include 'MySQLException.php';
- include 'MySQLResult.php';
- include 'MySQLStatement.php';
- // Connect
- try
- {
- $db = new MySQLDatabase("localhost", "db", "user", "***");
- }
- catch(MySQLException $e)
- {
- }
- // Pull something from our DB
- try
- {
- $result = $db -> query("SELECT news_title FROM ln_news");
- foreach($result as $row)
- {
- }
- }
- catch(MySQLException $e)
- {
- }
- // Preparing
- try
- {
- $db -> select_database('test');
- $statement = $db->prepare("INSERT INTO test.persons (name, age) VALUES (?, ?)");
- $statement -> bind_parameter(0, "Lucas van Dijk?"); // First ? in the query
- $statement -> bind_parameter(1, 16); // The second ?
- $db -> execute($statement);
- // Set new value
- $statement -> bind_parameter(0, "Ted's");
- $statement -> bind_parameter(1, 19);
- $db -> execute($statement);
- }
- catch(MySQLException $e)
- {
- }
- // With our own MySQL Statement
- try
- {
- $statement = new MySQLStatement("UPDATE persons SET age = :age WHERE name = :name");
- $statement -> bind_parameter(':age', 17);
- $statement -> bind_parameter(':name', 'Lucas van Dijk');
- $db -> execute($statement);
- }
- catch(MySQLException $e)
- {
- }
- $parse_time = $end_time - $start_time;

