模块

Database_PDO
继承自 Database

PDO 数据库连接。

package
BootPHP/数据库
category
驱动
author
Tinsh
copyright
© 2005-2016 Kilofox Studio

该类在 MODPATH/database/classes/database/pdo.php 第 13 行声明。

属性

public static string $default

default instance name

string(7) "default"

public static array $instances

Database instances

array(0) 

public string $last_query

the last query executed

public $tablePrefix

protected $_config

protected $_connection

protected $_identifier

protected $_instance

方法

public begin( [ string $mode = NULL ] ) (在 Database_PDO 中定义)

Start a SQL transaction // Start the transactions $db->begin(); try { DB::insert('users')->values($user1)... DB::insert('users')->values($user2)... // Insert successful commit the changes $db->commit(); } catch(Database_Exception $e) { // Insert failed. Rolling back changes... $db->rollback(); }

参数

  • string $mode = NULL - Transaction mode

返回值

  • boolean

源代码

public function begin($mode = NULL)
{
	// 确保数据库已连接
	$this->_connection || $this->connect();
	return $this->_connection->beginTransaction();
}

public commit( ) (在 Database_PDO 中定义)

提交当前事务 // Commit the database changes $db->commit();

返回值

  • boolean

源代码

public function commit()
{
	// 确保数据库已连接
	$this->_connection || $this->connect();
	return $this->_connection->commit();
}

public connect( ) (在 Database_PDO 中定义)

Connect to the database. This is called automatically when the first query is executed. $db->connect();

Tags

返回值

  • void

源代码

public function connect()
{
	if ($this->_connection)
		return;
	// 提取连接参数,添加需要的变量
	extract($this->_config['connection'] + array(
		'dsn' => '',
		'username' => NULL,
		'password' => NULL,
		'persistent' => false,
	));
	// 出于安全考虑,清除连接参数
	unset($this->_config['connection']);
	// 强制 PDO 对所有错误使用异常
	$attrs = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
	if ($persistent)
	{
		// 使连接持久
		$attrs[PDO::ATTR_PERSISTENT] = true;
	}
	try
	{
		// 创建一个新的 PDO 连接
		$this->_connection = new PDO($dsn, $username, $password, $attrs);
	}
	catch (PDOException $e)
	{
		throw new Database_Exception(':error', array(':error' => $e->getMessage()), $e->getCode());
	}
	if ($this->_config['charset'])
	{
		// 设置字符集
		$this->setCharset($this->_config['charset']);
	}
}

public create_aggregate( string $name , callback $step , callback $final [, integer $arguments = integer -1 ] ) (在 Database_PDO 中定义)

创建或重新定义一个SQL聚合函数。

仅适用于 SQLite

参数

  • string $name required - 要创建或重新定义的SQL函数名称
  • callback $step required - 被结果集的每一行调用
  • callback $final required - 结果集的所有行执行完毕后被调用
  • integer $arguments = integer -1 - SQL函数接受的参数数量

Tags

返回值

  • boolean

源代码

public function create_aggregate($name, $step, $final, $arguments = -1)
{
	$this->_connection || $this->connect();
	return $this->_connection->sqliteCreateAggregate(
			$name, $step, $final, $arguments
	);
}

public create_function( string $name , callback $callback [, integer $arguments = integer -1 ] ) (在 Database_PDO 中定义)

创建或重新定义一个SQL函数。

仅适用于 SQLite

参数

  • string $name required - 要创建或重新定义的SQL函数名称
  • callback $callback required - 实现SQL函数的回调
  • integer $arguments = integer -1 - SQL函数接受的参数数量

Tags

返回值

  • boolean

源代码

public function create_function($name, $callback, $arguments = -1)
{
	$this->_connection || $this->connect();
	return $this->_connection->sqliteCreateFunction(
			$name, $callback, $arguments
	);
}

public delete( string $table , string $where ) (在 Database_PDO 中定义)

执行 SQL 查询,用于删除一条记录。

参数

  • string $table required - 表名
  • string $where required - 查询条件

返回值

  • integer - 前一次SQL操作所影响的记录行数

源代码

public function delete($table, $where)
{
	$sql = "DELETE FROM `" . $this->tablePrefix . "$table` WHERE $where";
	return self::query('delete', $sql);
}

public disconnect( ) (在 Database_PDO 中定义)

Disconnect from the database. This is called automatically by Database::__destruct. Clears the database instance from Database::$instances. $db->disconnect();

返回值

  • boolean

源代码

public function disconnect()
{
	// 销毁 PDO 对象
	$this->_connection = NULL;
	return parent::disconnect();
}

public escape( string $value ) (在 Database_PDO 中定义)

Sanitize a string by escaping characters that could cause an SQL injection attack. $value = $db->escape('any string');

参数

  • string $value required - Value to quote

返回值

  • string

源代码

public function escape($value)
{
	// 确保数据库已连接
	$this->_connection || $this->connect();
	return $this->_connection->quote($value);
}

public insert( string $table , array $data ) (在 Database_PDO 中定义)

执行 SQL 查询,用于插入一条记录。

参数

  • string $table required - 表名
  • array $data required - 要插入的数据

返回值

  • integer - INSERT 查询产生的 ID 号

源代码

public function insert($table, $data)
{
	$fields = $values = '';
	foreach ($data as $k => $v)
	{
		$fields.= empty($fields) ? "`$k`" : ", `$k`";
		$values.= empty($values) ? "'$v'" : ", '$v'";
	}
	$sql = "INSERT INTO `" . $this->tablePrefix . "$table` ($fields) VALUES ($values)";
	return self::query('insert', $sql);
}

public list_columns( string $table [, string $like = NULL , boolean $add_prefix = bool true ] ) (在 Database_PDO 中定义)

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 from
  • string $like = NULL - Column to search for
  • boolean $add_prefix = bool true - Whether to add the table prefix automatically or not

返回值

  • array

源代码

public function list_columns($table, $like = NULL, $add_prefix = true)
{
	throw new BootPHP_Exception('Database method :method is not supported by :class', array(':method' => __FUNCTION__, ':class' => __CLASS__));
}

public list_tables( [ string $like = NULL ] ) (在 Database_PDO 中定义)

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 for

返回值

  • array

源代码

public function list_tables($like = NULL)
{
	throw new BootPHP_Exception('Database method :method is not supported by :class', array(':method' => __FUNCTION__, ':class' => __CLASS__));
}

public query( string $type , string $sql [, $as_object = bool false , $params = NULL ] ) (在 Database_PDO 中定义)

执行给定的类型的 SQL 查询。

// Make a SELECT query and use objects for results
$db->query('select', 'SELECT * FROM groups', true);
// Make a SELECT query and use "Model_User" for the results
$db->query('select', 'SELECT * FROM users LIMIT 1', 'Model_User');

参数

  • string $type required - 'select'、'insert' 等等
  • string $sql required - SQL 查询
  • unknown $as_object = bool false
  • unknown $params = NULL

返回值

  • object - SELECT 查询:结果
  • array - INSERT 查询:list(插入的 id, 行数)
  • integer - 其它查询:影响的行数

源代码

public function query($type, $sql, $as_object = false, array $params = NULL)
{
	// 确保数据库已连接
	$this->_connection || $this->connect();
	if (isset($this->_config['profiling']))
	{
		// Benchmark this query for the current instance
		$benchmark = Profiler::start("Database ({$this->_instance})", $sql);
	}
	try
	{
		$this->result = $this->_connection->query($sql);
	}
	catch (Exception $e)
	{
		if (isset($benchmark))
		{
			// This benchmark is worthless
			Profiler::delete($benchmark);
		}
		// Convert the exception in a database exception
		throw new Database_Exception(':error [ :query ]', array(
		':error' => $e->getMessage(),
		':query' => $sql
		), $e->getCode());
	}
	if (isset($benchmark))
	{
		Profiler::stop($benchmark);
	}
	// 设置最后一次查询
	$this->last_query = $sql;
	if ($type === 'select')
	{
		$this->result->setFetchMode(PDO::FETCH_CLASS, 'stdClass');
	}
	elseif ($type === 'insert')
	{
		// 返回插入的ID
		return $this->_connection->lastInsertId();
	}
	else
	{
		// 返回受影响的行数
		return $this->result->rowCount();
	}
}

public rollback( ) (在 Database_PDO 中定义)

Abort the current transaction // Undo the changes $db->rollback();

返回值

  • boolean

源代码

public function rollback()
{
	// 确保数据库已连接
	$this->_connection || $this->connect();
	return $this->_connection->rollBack();
}

public select( string $sql ) (在 Database_PDO 中定义)

执行 SQL 查询,并返回一个 stdClass 类型的记录。

参数

  • string $sql required - SQL查询

返回值

  • object - StdClass 类型的记录

源代码

public function select($sql)
{
	self::query('select', $sql);
	$this->result->setFetchMode(PDO::FETCH_OBJ);
	return $this->result->fetch();
}

public selectArray( string $sql ) (在 Database_PDO 中定义)

执行 SQL 查询,并返回一个由 stdClass 类型的记录构成的数组。

参数

  • string $sql required - SQL查询

返回值

  • array - StdClass 类型的记录构成的数组

源代码

public function selectArray($sql)
{
	self::query('select', $sql);
	$results = array();
	$this->result->setFetchMode(PDO::FETCH_OBJ);
	while ($obj = $this->result->fetch())
	{
		$results[] = $obj;
	}
	return $results;
}

public setCharset( string $charset ) (在 Database_PDO 中定义)

Set the connection character set. This is called automatically by Database::connect. $db->set_charset('utf8');

参数

  • string $charset required - Character set name

Tags

返回值

  • void

源代码

public function setCharset($charset)
{
	// 确保数据库已连接
	$this->_connection || $this->connect();
	// 这个 SQL-92 语法不是所有驱动都支持
	$this->_connection->exec('SET NAMES ' . $this->quote($charset));
}

public update( string $table , array $data , string $where ) (在 Database_PDO 中定义)

执行 SQL 查询,用于更新一条记录。

参数

  • string $table required - 表名
  • array $data required - 要更新的数据
  • string $where required - 查询条件

返回值

  • integer - 前一次SQL操作所影响的记录行数

源代码

public function update($table, $data, $where)
{
	$set = '';
	foreach ($data as $k => $v)
	{
		if (substr($v, 0, 2) == ':+' && is_numeric($len = substr($v, 2)))
			$v = "`$k` + $len";
		else if (substr($v, 0, 2) == ':-' && is_numeric($len = substr($v, 2)))
			$v = "`$k` - $len";
		else
			$v = "'$v'";
		$set.= "`$k` = $v, ";
	}
	$set = substr($set, 0, -2);
	$sql = "UPDATE `" . $this->tablePrefix . "$table` SET $set WHERE $where";
	return self::query('update', $sql);
}

final public __destruct( ) (在 Database 中定义)

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();
}

final public __toString( ) (在 Database 中定义)

Returns the database instance name. echo (string)$db;

返回值

  • string

源代码

final public function __toString()
{
	return $this->_instance;
}

public count_records( mixed $table ) (在 Database 中定义)

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('select', 'SELECT COUNT(*) AS total_row_count FROM ' . $table, false)
			->get('total_row_count');
}

public datatype( string $type ) (在 Database 中定义)

Returns a normalized array describing the SQL data type $db->datatype('char');

参数

  • string $type required - SQL data type

返回值

  • array

源代码

public function datatype($type)
{
	static $types = array
		(
		// SQL-92
		'bit' => array('type' => 'string', 'exact' => true),
		'bit varying' => array('type' => 'string'),
		'char' => array('type' => 'string', 'exact' => true),
		'char varying' => array('type' => 'string'),
		'character' => array('type' => 'string', 'exact' => true),
		'character varying' => array('type' => 'string'),
		'date' => array('type' => 'string'),
		'dec' => array('type' => 'float', 'exact' => true),
		'decimal' => array('type' => 'float', 'exact' => true),
		'double precision' => array('type' => 'float'),
		'float' => array('type' => 'float'),
		'int' => array('type' => 'int', 'min' => '-2147483648', 'max' => '2147483647'),
		'integer' => array('type' => 'int', 'min' => '-2147483648', 'max' => '2147483647'),
		'interval' => array('type' => 'string'),
		'national char' => array('type' => 'string', 'exact' => true),
		'national char varying' => array('type' => 'string'),
		'national character' => array('type' => 'string', 'exact' => true),
		'national character varying' => array('type' => 'string'),
		'nchar' => array('type' => 'string', 'exact' => true),
		'nchar varying' => array('type' => 'string'),
		'numeric' => array('type' => 'float', 'exact' => true),
		'real' => array('type' => 'float'),
		'smallint' => array('type' => 'int', 'min' => '-32768', 'max' => '32767'),
		'time' => array('type' => 'string'),
		'time with time zone' => array('type' => 'string'),
		'timestamp' => array('type' => 'string'),
		'timestamp with time zone' => array('type' => 'string'),
		'varchar' => array('type' => 'string'),
		// SQL:1999
		'binary large object' => array('type' => 'string', 'binary' => true),
		'blob' => array('type' => 'string', 'binary' => true),
		'boolean' => array('type' => 'bool'),
		'char large object' => array('type' => 'string'),
		'character large object' => array('type' => 'string'),
		'clob' => array('type' => 'string'),
		'national character large object' => array('type' => 'string'),
		'nchar large object' => array('type' => 'string'),
		'nclob' => array('type' => 'string'),
		'time without time zone' => array('type' => 'string'),
		'timestamp without time zone' => array('type' => 'string'),
		// SQL:2003
		'bigint' => array('type' => 'int', 'min' => '-9223372036854775808', 'max' => '9223372036854775807'),
		// SQL:2008
		'binary' => array('type' => 'string', 'binary' => true, 'exact' => true),
		'binary varying' => array('type' => 'string', 'binary' => true),
		'varbinary' => array('type' => 'string', 'binary' => true),
	);
	if (isset($types[$type]))
		return $types[$type];
	return array();
}

public static instance( [ string $name = NULL , array $config = NULL ] ) (在 Database 中定义)

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 name
  • array $config = NULL - Configuration parameters

返回值

  • Database

源代码

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 = BootPHP::$config->load('database')->$name;
		}
		if (!isset($config['type']))
		{
			throw new BootPHP_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];
}

public quote( mixed $value ) (在 Database 中定义)

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 quote

Tags

返回值

  • string

源代码

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);
}

public quote_column( mixed $column ) (在 Database 中定义)

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)

Tags

返回值

  • 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;
}

public quote_identifier( mixed $value ) (在 Database 中定义)

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 identifier

返回值

  • string

源代码

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;
}

public quote_table( mixed $table ) (在 Database 中定义)

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)

Tags

返回值

  • 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;
}

public table_prefix( ) (在 Database 中定义)

Return the table prefix defined in the current configuration. $prefix = $db->table_prefix();

返回值

  • string

源代码

public function table_prefix()
{
	return $this->_config['table_prefix'];
}

protected __construct( ) (在 Database_PDO 中定义)

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)
{
	parent::__construct($name, $config);
	if (isset($this->_config['identifier']))
	{
		// 让标识符在每个连接中都被重载
		$this->_identifier = (string) $this->_config['identifier'];
	}
}

protected _parse_type( string $type ) (在 Database 中定义)

Extracts the text between parentheses, if any. // Returns: array('CHAR', '6') list($type, $length) = $db->_parse_type('CHAR(6)');

参数

  • string $type required

返回值

  • array - List containing the type and length, if any

源代码

protected function _parse_type($type)
{
	if (($open = strpos($type, '(')) === false)
	{
		// No length specified
		return array($type, NULL);
	}
	// Closing parenthesis
	$close = strpos($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);
}