MySQL database connection.
Class declared in MODPATH/database/classes/kohana/database/mysql.php on line 11.
integer 1
integer 2
integer 3
integer 4
string
$defaultdefault instance name
string(7) "default"
array
$instancesDatabase instances
array(0)
string
$last_querythe last query executed
$_config
$_connection
$_connection_id
$_current_databasesarray(0)
$_identifier
$_instance
$_set_namesNULL
Start a SQL transaction
string
$mode
= NULL - Isolation levelboolean
public function begin($mode = NULL)
{
// Make sure the database is connected
$this->_connection or $this->connect();
if ($mode AND ! mysql_query("SET TRANSACTION ISOLATION LEVEL $mode", $this->_connection))
{
throw new Database_Exception(':error',
array(':error' => mysql_error($this->_connection)),
mysql_errno($this->_connection));
}
return (bool) mysql_query('START TRANSACTION', $this->_connection);
}
Commit a SQL transaction
boolean
public function commit()
{
// Make sure the database is connected
$this->_connection or $this->connect();
return (bool) mysql_query('COMMIT', $this->_connection);
}
Connect to the database. This is called automatically when the first query is executed.
$db->connect();
void
public function connect()
{
if ($this->_connection)
return;
if (Database_MySQL::$_set_names === NULL)
{
// Determine if we can use mysql_set_charset(), which is only
// available on PHP 5.2.3+ when compiled against MySQL 5.0+
Database_MySQL::$_set_names = ! function_exists('mysql_set_charset');
}
// Extract the connection parameters, adding required variabels
extract($this->_config['connection'] + array(
'database' => '',
'hostname' => '',
'username' => '',
'password' => '',
'persistent' => FALSE,
));
// Prevent this information from showing up in traces
unset($this->_config['connection']['username'], $this->_config['connection']['password']);
try
{
if ($persistent)
{
// Create a persistent connection
$this->_connection = mysql_pconnect($hostname, $username, $password);
}
else
{
// Create a connection and force it to be a new link
$this->_connection = mysql_connect($hostname, $username, $password, TRUE);
}
}
catch (Exception $e)
{
// No connection exists
$this->_connection = NULL;
throw new Database_Exception(':error',
array(':error' => $e->getMessage()),
$e->getCode());
}
// \xFF is a better delimiter, but the PHP driver uses underscore
$this->_connection_id = sha1($hostname.'_'.$username.'_'.$password);
$this->_select_db($database);
if ( ! empty($this->_config['charset']))
{
// Set the character set
$this->set_charset($this->_config['charset']);
}
if ( ! empty($this->_config['connection']['variables']))
{
// Set session variables
$variables = array();
foreach ($this->_config['connection']['variables'] as $var => $val)
{
$variables[] = 'SESSION '.$var.' = '.$this->quote($val);
}
mysql_query('SET '.implode(', ', $variables), $this->_connection);
}
}
Returns a normalized array describing the SQL data type
$db->datatype('char');
string
$type
required - SQL data typearray
public function datatype($type)
{
static $types = array
(
'blob' => array('type' => 'string', 'binary' => TRUE, 'character_maximum_length' => '65535'),
'bool' => array('type' => 'bool'),
'bigint unsigned' => array('type' => 'int', 'min' => '0', 'max' => '18446744073709551615'),
'datetime' => array('type' => 'string'),
'decimal unsigned' => array('type' => 'float', 'exact' => TRUE, 'min' => '0'),
'double' => array('type' => 'float'),
'double precision unsigned' => array('type' => 'float', 'min' => '0'),
'double unsigned' => array('type' => 'float', 'min' => '0'),
'enum' => array('type' => 'string'),
'fixed' => array('type' => 'float', 'exact' => TRUE),
'fixed unsigned' => array('type' => 'float', 'exact' => TRUE, 'min' => '0'),
'float unsigned' => array('type' => 'float', 'min' => '0'),
'int unsigned' => array('type' => 'int', 'min' => '0', 'max' => '4294967295'),
'integer unsigned' => array('type' => 'int', 'min' => '0', 'max' => '4294967295'),
'longblob' => array('type' => 'string', 'binary' => TRUE, 'character_maximum_length' => '4294967295'),
'longtext' => array('type' => 'string', 'character_maximum_length' => '4294967295'),
'mediumblob' => array('type' => 'string', 'binary' => TRUE, 'character_maximum_length' => '16777215'),
'mediumint' => array('type' => 'int', 'min' => '-8388608', 'max' => '8388607'),
'mediumint unsigned' => array('type' => 'int', 'min' => '0', 'max' => '16777215'),
'mediumtext' => array('type' => 'string', 'character_maximum_length' => '16777215'),
'national varchar' => array('type' => 'string'),
'numeric unsigned' => array('type' => 'float', 'exact' => TRUE, 'min' => '0'),
'nvarchar' => array('type' => 'string'),
'point' => array('type' => 'string', 'binary' => TRUE),
'real unsigned' => array('type' => 'float', 'min' => '0'),
'set' => array('type' => 'string'),
'smallint unsigned' => array('type' => 'int', 'min' => '0', 'max' => '65535'),
'text' => array('type' => 'string', 'character_maximum_length' => '65535'),
'tinyblob' => array('type' => 'string', 'binary' => TRUE, 'character_maximum_length' => '255'),
'tinyint' => array('type' => 'int', 'min' => '-128', 'max' => '127'),
'tinyint unsigned' => array('type' => 'int', 'min' => '0', 'max' => '255'),
'tinytext' => array('type' => 'string', 'character_maximum_length' => '255'),
'year' => array('type' => 'string'),
);
$type = str_replace(' zerofill', '', $type);
if (isset($types[$type]))
return $types[$type];
return parent::datatype($type);
}
Disconnect from the database. This is called automatically by Database::__destruct. Clears the database instance from Database::$instances.
$db->disconnect();
boolean
public function disconnect()
{
try
{
// Database is assumed disconnected
$status = TRUE;
if (is_resource($this->_connection))
{
if ($status = mysql_close($this->_connection))
{
// Clear the connection
$this->_connection = NULL;
// Clear the instance
parent::disconnect();
}
}
}
catch (Exception $e)
{
// Database is probably not disconnected
$status = ! is_resource($this->_connection);
}
return $status;
}
Sanitize a string by escaping characters that could cause an SQL injection attack.
$value = $db->escape('any string');
string
$value
required - Value to quotestring
public function escape($value)
{
// Make sure the database is connected
$this->_connection or $this->connect();
if (($value = mysql_real_escape_string( (string) $value, $this->_connection)) === FALSE)
{
throw new Database_Exception(':error',
array(':error' => mysql_error($this->_connection)),
mysql_errno($this->_connection));
}
// SQL standard is to use single-quotes for all values
return "'$value'";
}
Lists all of the columns in a table. Optionally, a LIKE string can be used to search for specific fields.
// Get all columns from the "users" table
$columns = $db->list_columns('users');
// Get all name-related columns
$columns = $db->list_columns('users', '%name%');
// Get the columns from a table that doesn't use the table prefix
$columns = $db->list_columns('users', NULL, FALSE);
string
$table
required - Table to get columns fromstring
$like
= NULL - Column to search forboolean
$add_prefix
= bool TRUE - Whether to add the table prefix automatically or notarray
public function list_columns($table, $like = NULL, $add_prefix = TRUE)
{
// Quote the table name
$table = ($add_prefix === TRUE) ? $this->quote_table($table) : $table;
if (is_string($like))
{
// Search for column names
$result = $this->query(Database::SELECT, 'SHOW FULL COLUMNS FROM '.$table.' LIKE '.$this->quote($like), FALSE);
}
else
{
// Find all column names
$result = $this->query(Database::SELECT, 'SHOW FULL COLUMNS FROM '.$table, FALSE);
}
$count = 0;
$columns = array();
foreach ($result as $row)
{
list($type, $length) = $this->_parse_type($row['Type']);
$column = $this->datatype($type);
$column['column_name'] = $row['Field'];
$column['column_default'] = $row['Default'];
$column['data_type'] = $type;
$column['is_nullable'] = ($row['Null'] == 'YES');
$column['ordinal_position'] = ++$count;
switch ($column['type'])
{
case 'float':
if (isset($length))
{
list($column['numeric_precision'], $column['numeric_scale']) = explode(',', $length);
}
break;
case 'int':
if (isset($length))
{
// MySQL attribute
$column['display'] = $length;
}
break;
case 'string':
switch ($column['data_type'])
{
case 'binary':
case 'varbinary':
$column['character_maximum_length'] = $length;
break;
case 'char':
case 'varchar':
$column['character_maximum_length'] = $length;
case 'text':
case 'tinytext':
case 'mediumtext':
case 'longtext':
$column['collation_name'] = $row['Collation'];
break;
case 'enum':
case 'set':
$column['collation_name'] = $row['Collation'];
$column['options'] = explode('\',\'', substr($length, 1, -1));
break;
}
break;
}
// MySQL attributes
$column['comment'] = $row['Comment'];
$column['extra'] = $row['Extra'];
$column['key'] = $row['Key'];
$column['privileges'] = $row['Privileges'];
$columns[$row['Field']] = $column;
}
return $columns;
}
List all of the tables in the database. Optionally, a LIKE string can be used to search for specific tables.
// Get all tables in the current database
$tables = $db->list_tables();
// Get all user-related tables
$tables = $db->list_tables('user%');
string
$like
= NULL - Table to search forarray
public function list_tables($like = NULL)
{
if (is_string($like))
{
// Search for table names
$result = $this->query(Database::SELECT, 'SHOW TABLES LIKE '.$this->quote($like), FALSE);
}
else
{
// Find all table names
$result = $this->query(Database::SELECT, 'SHOW TABLES', FALSE);
}
$tables = array();
foreach ($result as $row)
{
$tables[] = reset($row);
}
return $tables;
}
Perform an SQL query of the given type.
// Make a SELECT query and use objects for results
$db->query(Database::SELECT, 'SELECT * FROM groups', TRUE);
// Make a SELECT query and use "Model_User" for the results
$db->query(Database::SELECT, 'SELECT * FROM users LIMIT 1', 'Model_User');
integer
$type
required - Database::SELECT, Database::INSERT, etcstring
$sql
required - SQL querymixed
$as_object
= bool FALSE - Result object class string, TRUE for stdClass, FALSE for assoc arrayarray
$params
= NULL - Object construct parameters for result classobject
- Database_Result for SELECT queriesarray
- List (insert id, row count) for INSERT queriesinteger
- Number of affected rows for all other queriespublic function query($type, $sql, $as_object = FALSE, array $params = NULL)
{
// Make sure the database is connected
$this->_connection or $this->connect();
if ( ! empty($this->_config['profiling']))
{
// Benchmark this query for the current instance
$benchmark = Profiler::start("Database ({$this->_instance})", $sql);
}
if ( ! empty($this->_config['connection']['persistent']) AND $this->_config['connection']['database'] !== Database_MySQL::$_current_databases[$this->_connection_id])
{
// Select database on persistent connections
$this->_select_db($this->_config['connection']['database']);
}
// Execute the query
if (($result = mysql_query($sql, $this->_connection)) === FALSE)
{
if (isset($benchmark))
{
// This benchmark is worthless
Profiler::delete($benchmark);
}
throw new Database_Exception(':error [ :query ]',
array(':error' => mysql_error($this->_connection), ':query' => $sql),
mysql_errno($this->_connection));
}
if (isset($benchmark))
{
Profiler::stop($benchmark);
}
// Set the last query
$this->last_query = $sql;
if ($type === Database::SELECT)
{
// Return an iterator of results
return new Database_MySQL_Result($result, $sql, $as_object, $params);
}
elseif ($type === Database::INSERT)
{
// Return a list of insert id and rows created
return array(
mysql_insert_id($this->_connection),
mysql_affected_rows($this->_connection),
);
}
else
{
// Return the number of rows affected
return mysql_affected_rows($this->_connection);
}
}
Rollback a SQL transaction
boolean
public function rollback()
{
// Make sure the database is connected
$this->_connection or $this->connect();
return (bool) mysql_query('ROLLBACK', $this->_connection);
}
Set the connection character set. This is called automatically by Database::connect.
$db->set_charset('utf8');
string
$charset
required - Character set namevoid
public function set_charset($charset)
{
// Make sure the database is connected
$this->_connection or $this->connect();
if (Database_MySQL::$_set_names === TRUE)
{
// PHP is compiled against MySQL 4.x
$status = (bool) mysql_query('SET NAMES '.$this->quote($charset), $this->_connection);
}
else
{
// PHP is compiled against MySQL 5.x
$status = mysql_set_charset($charset, $this->_connection);
}
if ($status === FALSE)
{
throw new Database_Exception(':error',
array(':error' => mysql_error($this->_connection)),
mysql_errno($this->_connection));
}
}
Disconnect from the database when the object is destroyed.
// Destroy the database instance
unset(Database::instances[(string) $db], $db);
Calling unset($db)
is not enough to destroy the database, as it
will still be stored in Database::$instances
.
void
final public function __destruct()
{
$this->disconnect();
}
Returns the database instance name.
echo (string) $db;
string
final public function __toString()
{
return $this->_instance;
}
Count the number of records in a table.
// Get the total number of records in the "users" table
$count = $db->count_records('users');
mixed
$table
required - Table name string or array(query, alias)integer
public function count_records($table)
{
// Quote the table name
$table = $this->quote_table($table);
return $this->query(Database::SELECT, 'SELECT COUNT(*) AS total_row_count FROM '.$table, FALSE)
->get('total_row_count');
}
Get a singleton Database instance. If configuration is not specified, it will be loaded from the database configuration file using the same group as the name.
// Load the default database
$db = Database::instance();
// Create a custom configured instance
$db = Database::instance('custom', $config);
string
$name
= NULL - Instance namearray
$config
= NULL - Configuration parametersDatabase
public static function instance($name = NULL, array $config = NULL)
{
if ($name === NULL)
{
// Use the default instance name
$name = Database::$default;
}
if ( ! isset(Database::$instances[$name]))
{
if ($config === NULL)
{
// Load the configuration for this database
$config = Kohana::$config->load('database')->$name;
}
if ( ! isset($config['type']))
{
throw new Kohana_Exception('Database type not defined in :name configuration',
array(':name' => $name));
}
// Set the driver class name
$driver = 'Database_'.ucfirst($config['type']);
// Create the database connection instance
new $driver($name, $config);
}
return Database::$instances[$name];
}
Quote a value for an SQL query.
$db->quote(NULL); // 'NULL'
$db->quote(10); // 10
$db->quote('fred'); // 'fred'
Objects passed to this function will be converted to strings.
Database_Expression objects will be compiled.
Database_Query objects will be compiled and converted to a sub-query.
All other objects will be converted using the __toString
method.
mixed
$value
required - Any value to quotestring
public function quote($value)
{
if ($value === NULL)
{
return 'NULL';
}
elseif ($value === TRUE)
{
return "'1'";
}
elseif ($value === FALSE)
{
return "'0'";
}
elseif (is_object($value))
{
if ($value instanceof Database_Query)
{
// Create a sub-query
return '('.$value->compile($this).')';
}
elseif ($value instanceof Database_Expression)
{
// Compile the expression
return $value->compile($this);
}
else
{
// Convert the object to a string
return $this->quote( (string) $value);
}
}
elseif (is_array($value))
{
return '('.implode(', ', array_map(array($this, __FUNCTION__), $value)).')';
}
elseif (is_int($value))
{
return (int) $value;
}
elseif (is_float($value))
{
// Convert to non-locale aware float to prevent possible commas
return sprintf('%F', $value);
}
return $this->escape($value);
}
Quote a database column name and add the table prefix if needed.
$column = $db->quote_column($column);
You can also use SQL methods within identifiers.
// The value of "column" will be quoted
$column = $db->quote_column('COUNT("column")');
Objects passed to this function will be converted to strings.
Database_Expression objects will be compiled.
Database_Query objects will be compiled and converted to a sub-query.
All other objects will be converted using the __toString
method.
mixed
$column
required - Column name or array(column, alias)string
public function quote_column($column)
{
if (is_array($column))
{
list($column, $alias) = $column;
}
if ($column instanceof Database_Query)
{
// Create a sub-query
$column = '('.$column->compile($this).')';
}
elseif ($column instanceof Database_Expression)
{
// Compile the expression
$column = $column->compile($this);
}
else
{
// Convert to a string
$column = (string) $column;
if ($column === '*')
{
return $column;
}
elseif (strpos($column, '"') !== FALSE)
{
// Quote the column in FUNC("column") identifiers
$column = preg_replace('/"(.+?)"/e', '$this->quote_column("$1")', $column);
}
elseif (strpos($column, '.') !== FALSE)
{
$parts = explode('.', $column);
if ($prefix = $this->table_prefix())
{
// Get the offset of the table name, 2nd-to-last part
$offset = count($parts) - 2;
// Add the table prefix to the table name
$parts[$offset] = $prefix.$parts[$offset];
}
foreach ($parts as & $part)
{
if ($part !== '*')
{
// Quote each of the parts
$part = $this->_identifier.$part.$this->_identifier;
}
}
$column = implode('.', $parts);
}
else
{
$column = $this->_identifier.$column.$this->_identifier;
}
}
if (isset($alias))
{
$column .= ' AS '.$this->_identifier.$alias.$this->_identifier;
}
return $column;
}
Quote a database identifier
Objects passed to this function will be converted to strings.
Database_Expression objects will be compiled.
Database_Query objects will be compiled and converted to a sub-query.
All other objects will be converted using the __toString
method.
mixed
$value
required - Any identifierstring
public function quote_identifier($value)
{
if (is_array($value))
{
list($value, $alias) = $value;
}
if ($value instanceof Database_Query)
{
// Create a sub-query
$value = '('.$value->compile($this).')';
}
elseif ($value instanceof Database_Expression)
{
// Compile the expression
$value = $value->compile($this);
}
else
{
// Convert to a string
$value = (string) $value;
if (strpos($value, '.') !== FALSE)
{
$parts = explode('.', $value);
foreach ($parts as & $part)
{
// Quote each of the parts
$part = $this->_identifier.$part.$this->_identifier;
}
$value = implode('.', $parts);
}
else
{
$value = $this->_identifier.$value.$this->_identifier;
}
}
if (isset($alias))
{
$value .= ' AS '.$this->_identifier.$alias.$this->_identifier;
}
return $value;
}
Quote a database table name and adds the table prefix if needed.
$table = $db->quote_table($table);
Objects passed to this function will be converted to strings.
Database_Expression objects will be compiled.
Database_Query objects will be compiled and converted to a sub-query.
All other objects will be converted using the __toString
method.
mixed
$table
required - Table name or array(table, alias)string
public function quote_table($table)
{
if (is_array($table))
{
list($table, $alias) = $table;
}
if ($table instanceof Database_Query)
{
// Create a sub-query
$table = '('.$table->compile($this).')';
}
elseif ($table instanceof Database_Expression)
{
// Compile the expression
$table = $table->compile($this);
}
else
{
// Convert to a string
$table = (string) $table;
if (strpos($table, '.') !== FALSE)
{
$parts = explode('.', $table);
if ($prefix = $this->table_prefix())
{
// Get the offset of the table name, last part
$offset = count($parts) - 1;
// Add the table prefix to the table name
$parts[$offset] = $prefix.$parts[$offset];
}
foreach ($parts as & $part)
{
// Quote each of the parts
$part = $this->_identifier.$part.$this->_identifier;
}
$table = implode('.', $parts);
}
else
{
// Add the table prefix
$table = $this->_identifier.$this->table_prefix().$table.$this->_identifier;
}
}
if (isset($alias))
{
// Attach table prefix to alias
$table .= ' AS '.$this->_identifier.$this->table_prefix().$alias.$this->_identifier;
}
return $table;
}
Return the table prefix defined in the current configuration.
$prefix = $db->table_prefix();
string
public function table_prefix()
{
return $this->_config['table_prefix'];
}
Select the database
string
$database
required - Databasevoid
protected function _select_db($database)
{
if ( ! mysql_select_db($database, $this->_connection))
{
// Unable to select database
throw new Database_Exception(':error',
array(':error' => mysql_error($this->_connection)),
mysql_errno($this->_connection));
}
Database_MySQL::$_current_databases[$this->_connection_id] = $database;
}
Stores the database configuration locally and name the instance.
This method cannot be accessed directly, you must use Database::instance.
void
protected function __construct($name, array $config)
{
// Set the instance name
$this->_instance = $name;
// Store the config locally
$this->_config = $config;
if (empty($this->_config['table_prefix']))
{
$this->_config['table_prefix'] = '';
}
// Store the database instance
Database::$instances[$name] = $this;
}
Extracts the text between parentheses, if any.
// Returns: array('CHAR', '6')
list($type, $length) = $db->_parse_type('CHAR(6)');
string
$type
required - $typearray
- List containing the type and length, if anyprotected function _parse_type($type)
{
if (($open = strpos($type, '(')) === FALSE)
{
// No length specified
return array($type, NULL);
}
// Closing parenthesis
$close = strrpos($type, ')', $open);
// Length without parentheses
$length = substr($type, $open + 1, $close - 1 - $open);
// Type without the length
$type = substr($type, 0, $open).substr($type, $close + 1);
return array($type, $length);
}