falseclock/dbd-php

PHP 数据库驱动程序(PostgreSQL、MySQL、MSSQL、OData、YellowERP、1С)

3.1.1 2024-06-13 14:05 UTC

README

PHP Coverage Status PHP Version Require

Latest Stable Version Total Downloads Latest Unstable Version License

为什么不是标准的PDO?

实际上,这个库的开发是在PHP 5.0之前开始的。作为一个主要使用Perl的开发者,并受到DBI::DBD库的启发,我尝试为PHP开发相同的功能。

基本功能列表

  • 比PDO更舒适、更简单
  • SQL注入防护
  • 类似DBD/DBI的Perl库
  • 易于缓存集成
  • 更好的错误处理
  • 测量和调试
  • 可由其他驱动程序扩展(只有PostgreSQL完全准备好)
  • 使用dbd-php-entity库自动将记录转换为对象

获取实例

非常非常简单

<?php
use DBD\Common\Config;
use DBD\Pg;

$config = new Config("127.0.0.1", 5432, "db_name", "user_name", "user_password");

$dbh =  new Pg($config);
$dbh->connect();

/*
... do some stuff
*/

$dbh->disconnect();
?>

基本方法

connect

connect — 初始化到数据库的连接

描述

resource connect ()

connect() 使用在构造中提供的 Option 实例打开到数据库的连接。

do

do — 返回受影响的记录数(元组)

描述

int do ( string $statement [, mixed $params ] )

do() 返回由INSERT、UPDATE和DELETE查询影响的元组(实例/记录/行)的数量。

从PostgreSQL 9.0及以上版本开始,服务器返回所选行的数量。较老的PostgreSQL返回0。

参数

statement

要执行的SQL语句。可以包含占位符。只能包含单个语句(用分号分隔的多个语句是不允许的)。如果使用任何参数,它们将作为 ?, ?, 等. 引用。

params

一个参数值数组,用于替换原始准备好的SQL语句字符串中的 ?, ?, 等. 占位符。数组中的元素数量必须与占位符数量匹配。

示例

<?php
use DBD\Common\Config;
use DBD\Pg;

$config = new Config("127.0.0.1", 5432, "db_name", "user_name", "user_password");

$db =  new Pg($config);
$db->connect();

// The following example is insecure against SQL injections
$param = "'must be null'";
$result = $db->do("UPDATE table SET column1 = NULL WHERE column2 = $param");

// more easiest, simple and safe for SQL injections example.
// Number of affected tuples will be stored in $result variable
$result = $db->do("UPDATE table SET column1 = ? WHERE column2 = ?", NULL, 'must be null');
?>

query

query — 快速语句执行

描述

resource query ( string $statement [, mixed $params ] )

query()do() 方法执行相同,但返回self实例。

参数

statement

要执行的SQL语句。可以包含占位符。只能包含单个语句(用分号分隔的多个语句是不允许的)。如果使用任何参数,它们将作为 ?, ?, 等. 引用。

params

一个参数值数组,用于替换原始准备好的SQL语句字符串中的 ?, ?, 等. 占位符。数组中的元素数量必须与占位符数量匹配。

示例

<?php
use DBD\Pg;
/** @var Pg $db */
$sth = $db->query("SELECT * FROM invoices");

while ($row = $sth->fetchRow()) {
	echo($row['invoice_id']);
}

$sth = $db->query("UPDATE invoices SET invoice_uuid = ?",'550e8400-e29b-41d4-a716-446655440000');

echo($sth->affectedRows());

?>

prepare

prepare — 使用 execute() 方法创建用于以后执行的准备好的语句。此功能允许重复使用的命令仅解析和计划一次,而不是每次执行时都进行。

描述

resource prepare ( string $statement )

prepare() 返回新的DB驱动程序实例。

参数

statement

要执行的SQL语句。可以包含占位符。只能包含单个语句(用分号分隔的多个语句是不允许的)。如果使用任何参数,它们将作为 ?, ?, 等. 引用。

示例

<?php
use DBD\Pg;
/** @var Pg $db */
// Common usage for repeatedly SELECT queries
$sth = $db->prepare("UPDATE table SET column1 = ? WHERE column2 = ?");

$fruits = array('apple','banana','apricot');

foreach ($fruits as $fruit) {
	$sth->execute(NULL,$fruit);
}

/*
this code will execute three statements
UPDATE table SET column1 = NULL WHERE column2 = 'apple';
UPDATE table SET column1 = NULL WHERE column2 = 'banana';
UPDATE table SET column1 = NULL WHERE column2 = 'apricot';
*/
?>

execute

execute — 发送请求执行带有给定参数的准备好的语句,并等待结果。

描述

resource execute ( [ mixed $params ] )

execute() 执行之前准备好的语句,而不是提供查询字符串。此功能允许重复使用的命令仅解析和计划一次,而不是每次执行时都进行。语句必须已经准备好。

参数

params

一个参数值数组,用于替换原始准备好的查询字符串中的 ?, ?, 等. 占位符。数组中的元素数量必须与占位符数量匹配。

示例

<?php
use DBD\Pg;
/** @var Pg $db */

// Common usage for repeatedly UPDATE queries
$sth = $db->prepare("SELECT col1, col2, col3 FROM table1");
$std = $db->prepare("UPDATE table2 SET col2 =? WHERE col1=? AND col2=?");

$sth->execute();

while ($row = $sth->fetchRow()) {
	if ($row['col1'] == 'banana') {
    	$std->execute(FALSE, NULL, $row['col2']);
    }
}
/*
this code will execute this statement
UPDATE table2 SET col2 = FALSE WHERE col1 = NULL AND col2 = <value of col2 from table1>;
*/
?>

fetch

fetch — 从第一行获取列。

描述

mixed fetch ()

fetch() 从第一行获取列,而不获取整个行或减少结果。调用 fetchrow() 或 fetchrowset() 仍将返回整个结果集。后续的 fetch() 调用将返回行中的下一列。当您需要获取所有行中相同的列的值时非常有用。

示例

<?php
use DBD\Pg;
/** @var Pg $db */
$sth = $db->prepare("SELECT 'VIR-TEX LLC' AS company, generate_series AS wrh_id, 'Warehouse #'||trunc(random()*1000) AS wrh_name, trunc((random()*1000)::numeric, 2) AS wrh_volume FROM generate_series(1,3)");

/* select result example
   company   | wrh_id |    wrh_name    | wrh_volume
-------------+--------+----------------+------------
 VIR-TEX LLP |      1 | Warehouse #845 |     489.20
 VIR-TEX LLP |      2 | Warehouse #790 |     241.80
 VIR-TEX LLP |      3 | Warehouse #509 |     745.29
*/

$sth->execute();

$company_name = $sth->fetch(); // getting first column
$wrh_id = $sth->fetch(); // getting second column as an example of subsequent invoking
$wrh_name = $sth->fetch(); // getting third column

echo ("Company name: $company_name\n");

while ($row = $sth->fetchRow()) {
	echo("	{$row['wrh_name']} volume {$row['wrh_volume']}\n");
}

/* cycle above will produce following printout
Company name: VIR-TEX LLP
	Warehouse #845 volume: 489.20
	Warehouse #790 volume: 241.80
	Warehouse #509 volume: 745.29
*/
?>

fetchrow

fetchRow — 以关联数组的形式获取一行

描述

array fetchRow ()

fetchRow() 返回一个关联数组,该数组对应于获取的行(记录)。

返回值

一个通过字段名称索引的关联数组。数组中的每个值都表示为一个字符串。数据库 NULL 值作为 NULL 返回。

如果行超过集合中的行数、没有更多行或发生任何其他错误,则返回 FALSE。

示例

<?php
use DBD\Pg;
/** @var Pg $db */
$sth = $db->prepare("SELECT *, 'orange' AS col1, 'apple' AS col2, 'tomato'  AS col3 FROM generate_series(1,3)");
$sth->execute();
print_r($sth->fetchrow());

/* code above will produce following printout
Array
(
    [generate_series] => 1
    [col1] => orange
    [col2] => apple
    [col3] => tomato
)
*/
?>

fetchrowset

fetchRowSet — 以多维数组的形式获取整个结果,其中每个元素都是一个关联数组,对应于获取的行。

描述

array fetchRowSet ([ string $key ])

参数

key

用作索引的列名。如果有两个或多个列在同一列中具有相同的值,则数组中只存储最后一行。

返回值

如果提供了 key,则返回一个关联数组;如果没有提供 key,则返回一个索引数组。数组中的每个值都表示为一个关联数组(按字段名称)。行中的数据库 NULL 值作为 NULL 返回。

示例

<?php
use DBD\Pg;
/** @var Pg $db */
$sth = $db->prepare("SELECT generate_series AS wrh_id, 'Warehouse #'||trunc(random()*1000) AS wrh_name, trunc((random()*1000)::numeric, 2) AS wrh_volume FROM generate_series(1,3)");
$sth->execute();
print_r($sth->fetchRowSet());

/* code above will produce following printout
Array
(
    [0] => Array
        (
            [wrh_id] => 1
            [wrh_name] => Warehouse #795
            [wrh_volume] => 809.73
        )

    [1] => Array
        (
            [wrh_id] => 2
            [wrh_name] => Warehouse #639
            [wrh_volume] => 894.50
        )

    [2] => Array
        (
            [wrh_id] => 3
            [wrh_name] => Warehouse #334
            [wrh_volume] => 13.77
        )

)
*/

$sth->execute();
print_r($sth->fetchRowSet('wrh_name'));

/*
Array
(
    [Warehouse #214] => Array
        (
            [wrh_id] => 1
            [wrh_name] => Warehouse #214
            [wrh_volume] => 462.10
        )

    [Warehouse #563] => Array
        (
            [wrh_id] => 2
            [wrh_name] => Warehouse #563
            [wrh_volume] => 8.88
        )

    [Warehouse #634] => Array
        (
            [wrh_id] => 3
            [wrh_name] => Warehouse #634
            [wrh_volume] => 338.18
        )

)
*/
?>

insert

insert — 将新行插入到表中。返回自实例。

描述

mixed insert (string $table, array $values [, string $return])

参数

table

数据表名称

values

一个关联数组,其中键是字段名称,值是字段值。

return

您可以在成功插入后定义希望返回的表字段。

示例 1

<?php
use DBD\Pg;
/** @var Pg $db */
/** @var array $doc */
$record = [
	'invoice_uuid' => $doc['Ref'],
	'invoice_date' => $doc['Date'],
	'invoice_number' => $doc['Number'],
	'invoice_amount' => $doc['Amount'],
	'waybill_uuid' => $doc['reference']['uuid']
];
$sth = $db->insert('vatInvoices',$record);
echo ($sth->affectedRows());

?>

示例 2

<?php
use DBD\Pg;
/** @var Pg $db */
/** @var array $payment */
$record = [
	//'payment_id' => IS SERIAL, will be generated automatically
	'payment_uuid' => $payment['Ref'],
	'payment_date' => $payment['Date'],
	'payment_number' => $payment['Number'],
	'payment_amount' => $payment['Amount']
];

$sth = $db->insert('payments', $record, 'payment_id, payment_uuid');

while ($row = $sth->fetchrow()) {
	printf("We inserted new payment with ID=%d and UUID=%s\n",$row['payment_id'],$row['payment_uuid']);
}
?>

update

update — 通过给定的参数和预定义的值进行行更新。返回自实例。

描述

mixed update (string $table, array $values [, mixed $where..., [ mixed $args...], [string $return]])

参数

table

数据表名称

values

一个关联数组,其中键是字段名称,值是字段值。

where

指定更新条件。可以有占位符。

args

where 条件绑定值。如果 where 参数中存在占位符,则严格。如果没有在 where 参数中存在占位符,则可以省略。

return

您可以在成功插入后定义希望返回的表字段。

示例 1

<?php
use DBD\Pg;
/** @var Pg $db */
/** @var array $doc */
$update = [
	'invoice_date' => $doc['Date'],
	'invoice_number' => $doc['Number'],
	'invoice_amount' => $doc['Amount']
];
/* this will update all rows in a table */
$sth = $db->update('invoices',$update);
echo ($sth->affectedRows());
?>

示例 2

<?php
use DBD\Pg;
/** @var Pg $db */
/** @var array $doc */
$update = [
	'invoice_date' => $doc['Date'],
	'invoice_number' => $doc['Number'],
	'invoice_amount' => $doc['Amount']
];
/* this will update all rows in a table where vat_invoice_uuid equals to some value */
$sth = $db->update('vat_invoices', $update, "vat_invoice_uuid=?", $doc['UUID']);
echo ($sth->affectedRows());
?>

示例 3

<?php
use DBD\Pg;
/** @var Pg $db */
/** @var array $doc */
$update = array(
	'vatinvoice_date' => $doc['Date'],
	'vatinvoice_number' => $doc['Number'],
	'vatinvoice_amount' => $doc['Amount']
);
/* 
this will update all rows in a table where vatinvoice_uuid is null
query will return vatinvoice_id
*/
$sth = $db->update('vatinvoices', $update, "vatinvoice_uuid IS NULL", "vatinvoice_id");
while ($row = $sth->fetchRow()) {
	printf("Updated vatinvoice with ID=%d\n", $row['vatinvoice_id']);
}
?>

示例 4

<?php
use DBD\Pg;
/** @var Pg $db */
/** @var array $doc */
$update = array(
	'vatinvoice_date' => $doc['Date'],
	'vatinvoice_number' => $doc['Number'],
	'vatinvoice_amount' => $doc['Amount']
);
// this will update all rows in a table where vatinvoice_uuid equals to some value
// query will return vatinvoice_id
$sth = $db->update('vatinvoices',$update,"vatinvoice_uuid =? ", $doc['UUID'], "vatinvoice_id, vatinvoice_uuid");
while ($row = $sth->fetchRow()) {
	printf("Updated vatinvoice with ID=%d and UUID=%s\n",$row['vatinvoice_id'],$row['vatinvoice_uuid']);
}
?>

begin

begin — 开始数据库事务

描述

mixed begin ()

begin() 禁用自动提交(通过关闭自动提交),直到下一次调用 commitrollback。在调用 commitrollback 之后,自动提交将自动再次打开。

示例

<?php
use DBD\Pg;
/** @var Pg $db */

$db->begin();

// Common usage for repeatedly UPDATE queries
$sth = $db->prepare("SELECT col1, col2, col3 FROM table1");
$std = $db->prepare("UPDATE table2 SET col2 =? WHERE col1=? AND col2=?");

$sth->execute();

while ($row = $sth->fetchrow()) {
	if ($row['col1'] == 'banana') {
    	$std->execute(FALSE,NULL,$row['col2']);
    }
}
$db->commit();
?>

commit

commit — 提交数据库事务

描述

mixed commit ()

commit() 如果数据库支持事务且自动提交关闭,则使最近的数据库更改永久化。

rollback

rollback — 撤销更改

描述

mixed rollback ()

rollback() 如果数据库支持事务且自动提交关闭,则撤销最近的未提交的数据库更改。

cache

cache — 缓存选择结果

描述

mixed cache ()

cache() bla bla la