PDO 类
(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.1.0)
简介
代表 PHP 和数据库服务之间的连接
类摘要
class PDO
{
/* 常量 */
/* 方法 */
public __construct(
string
?string
#[\SensitiveParameter] ?string
?array
)
string
$dsn
,?string
$username
= null
,#[\SensitiveParameter] ?string
$password
= null
,?array
$options
= null
)
public static connect(
string
?string
#[\SensitiveParameter] ?string
?array
): static
}string
$dsn
,?string
$username
= null
,#[\SensitiveParameter] ?string
$password
= null
,?array
$options
= null
): static
更新日志
版本 | 说明 |
---|---|
8.4.0 | 类常量现已类型化。 |
目录
- PDO::beginTransaction — 启动一个事务
- PDO::commit — 提交一个事务
- PDO::connect — Connect to a database and return a PDO subclass for drivers that support it
- PDO::__construct — 创建一个表示数据库连接的 PDO 实例
- PDO::errorCode — 获取跟数据库句柄上一次操作相关的 SQLSTATE
- PDO::errorInfo — Fetch extended error information associated with the last operation on the database handle
- PDO::exec — 执行 SQL 语句,并返回受影响的行数
- PDO::getAttribute — 取回一个数据库连接的属性
- PDO::getAvailableDrivers — 返回一个可用驱动的数组
- PDO::inTransaction — 检查是否在事务内
- PDO::lastInsertId — 返回最后插入行的ID或序列值
- PDO::prepare — 预处理要执行的语句,并返回语句对象
- PDO::query — 预处理并执行没有占位符的 SQL 语句
- PDO::quote — 为 SQL 查询里的字符串添加引号
- PDO::rollBack — 回滚事务
- PDO::setAttribute — 设置属性
+添加备注
用户贡献的备注 6 notes
Megaloman ¶
16 years ago
"And storing username/password inside class is not a very good idea for production code."
Good idea is to store database connection settings in *.ini files but you have to restrict access to them. For example this way:
my_setting.ini:
[database]
driver = mysql
host = localhost
;port = 3306
schema = db_schema
username = user
password = secret
Database connection:
<?php
class MyPDO extends PDO
{
public function __construct($file = 'my_setting.ini')
{
if (!$settings = parse_ini_file($file, TRUE)) throw new exception('Unable to open ' . $file . '.');
$dns = $settings['database']['driver'] .
':host=' . $settings['database']['host'] .
((!empty($settings['database']['port'])) ? (';port=' . $settings['database']['port']) : '') .
';dbname=' . $settings['database']['schema'];
parent::__construct($dns, $settings['database']['username'], $settings['database']['password']);
}
}
?>
Database connection parameters are accessible via human readable ini file for those who screams even if they see one PHP/HTML/any_other command.
anrdaemon at freemail dot ru ¶
16 years ago
Keep in mind, you MUST NOT use 'root' user in your applications, unless your application designed to do a database maintenance.
And storing username/password inside class is not a very good idea for production code. You would need to edit the actual working code to change settings, which is bad.
williambarry007 at gmail dot com ¶
13 years ago
PDO and Dependency Injection
Dependency injection is good for testing. But for anyone wanting various data mapper objects to have a database connection, dependency injection can make other model code very messy because database objects have to be instantiated all over the place and given to the data mapper objects.
The code below is a good way to maintain dependency injection while keeping clean and minimal model code.
<?php
class DataMapper
{
public static $db;
public static function init($db)
{
self::$db = $db;
}
}
class VendorMapper extends DataMapper
{
public static function add($vendor)
{
$st = self::$db->prepare(
"insert into vendors set
first_name = :first_name,
last_name = :last_name"
);
$st->execute(array(
':first_name' => $vendor->first_name,
':last_name' => $vendor->last_name
));
}
}
// In your bootstrap
$db = new PDO(...);
DataMapper::init($db);
// In your model logic
$vendor = new Vendor('John', 'Doe');
VendorMapper::add($vendor);
?>
thz at plista dot com ¶
11 years ago
Starting with PHP 5.4 you are unable to use persistent connections when you have your own database class derived from the native PDO class. If your code uses this combination, you will encounter segmentation faults during the cleanup of the PHP process.
You can still use _either_ a derived PDO class _or_ persistent connections.
For more information, please see this bug report: https://bugs.php.net/bug.php?id=63176
sinri at everstray dot com ¶
7 years ago
For some Database Environment, such as Aliyun DRDS (Distributed Relational Database Service), cannot process preparing for SQL.
For such cases, the option `\PDO::ATTR_EMULATE_PREPARES` should be set to true. If you always got reports about "Failed to prepare SQL" while this option were set to false, you might try to turn on this option to emulate prepares for SQL.
Anonymous ¶
7 years ago
I personnaly create a new instance of PDO like this :
$dbDatas = parse_ini_file( DB_FILE );
$dbOptions = [
\PDO::ATTR_DEFAULT_FECTH_MODE => \PDO::FETCH_OBJ,
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION
];
$dsn = sprintf( 'mysql:dbname=%s;host=%s', $dbDatas['dbname'],
$dbDatas['host'] );
$this->cn = new \PDO( $dsn, $dbDatas['user'], $dbDatas['password'],
$dbOptions );
$this->cn->exec( 'SET CHARACTER SET UTF8' );