DSN連接方式
DB目前支持的連接方式如下
最完整的格式:
phptype(dbsyntax)://username:password@protocol+hostspec/database?option=value
別外還有一些縮寫(xiě)的格式:
phptype://username:password@protocol+hostspec:110//usr/db_file.db
phptype://username:password@hostspec/database
phptype://username:password@hostspec
phptype://username@hostspec
phptype://hostspec/database
phptype://hostspec
phptype:///database
phptype:///database?option=value&anotheroption=anothervalue
phptype(dbsyntax)
phptype
其中phptype表示數據庫類(lèi)型,可用的選項有:
dbase -> dBase
fbsql -> FrontBase
ibase -> InterBase
ifx -> Informix
msql -> Mini SQL
mssql -> Microsoft SQL Server
mysql -> MySQL (for MySQL <= 4.0)
mysqli -> MySQL (for MySQL >= 4.1) (since DB 1.6.3)
oci8 -> Oracle 7/8/9
odbc -> ODBC (Open Database Connectivity)
pgsql -> PostgreSQL
sqlite -> SQLite
sybase -> Sybase
以下是一些常用的連接例子:
l 連到一非標準端口的數據庫
pgsql://user:pass@tcp(localhost:5555)/pear
l 通過(guò)SOCKET方式連到數據庫
mysql://user@unix(/path/to/socket)/pear
l 在UNIX機上,連接SQLite數據庫
sqlite:////full/unix/path/to/file.db?mode=0666
l 在Windows機上,連接SQLite數據庫
sqlite:///c:/full/windows/path/to/file.db?mode=0666
l 使用SSL,連接到MySQLi
mysqli://user:pass@localhost/pear?key=client-key.pem&cert=client-cert.pem
l 通過(guò)ODBC連接到一個(gè)ACCESS數據庫
odbc(access)://username:password@/datasourcename
DB連接實(shí)例
<?php
require_once ‘DB.php‘;
$dsn = ‘mysql://username:password@localhost/dbname‘;
/**
也可以用以下的方式
$dsn = array(
‘phptype‘ => ‘pgsql‘,
‘username‘ => ‘someuser‘,
‘password‘ => ‘a(chǎn)passwd‘,
‘hostspec‘ => ‘localhost‘,
‘database‘ => ‘thedb‘,
);
*/
//$options是可選的
$options = array(
‘debug‘ => 2,
‘portability‘ => DB_PORTABILITY_ALL,
);
$db =& DB::connect($dsn, $options);
if (DB::isError($db)) {
die($db->getMessage());
}
//設置數據庫的默認查詢(xún)方式
$db->setFetchMode(DB_FETCHMODE_ASSOC);
//執行一個(gè)普通的查詢(xún)語(yǔ)句
$res =& $db->query(‘SELECT * FROM products‘);
//取得一個(gè)SQL查詢(xún)的結果集行,列數
printf("共有%d行,%d列數據", $res->numRows(), $res->numCols());
//當前表的結構信息
echo ("<pre>");
print_r($db->tableInfo($res));
echo ("</pre>");
//執行一個(gè)帶參數的查詢(xún)
$sql = ‘select * from products where products_id < ?‘;
$data = 50;
$res =& $db->query($sql, $data);
//執行含有多個(gè)參數的查詢(xún)
$sql = ‘select * from products where products_volt < ? and products_capacity > ?‘;
$data = array(10, 4000);
$res =& $db->query($sql, $data);
// 記得永遠要檢查執行的動(dòng)作是否有錯誤
if (DB::isError($res)) {
die($res->getMessage());
}
//按默認方式DB_FETCHMODE_ORDERED,循環(huán)顯示,輸出結果,這種方式下,只能以序號的方式來(lái)訪(fǎng)問(wèn)數據字段
while ($row =& $res->fetchRow()) {
echo $row[0] . "<br />\n";
}
//按DB_FETCHMODE_ASSOC方式,循環(huán)顯示,輸出結果,這種方式下,以字段名稱(chēng)的方式來(lái)訪(fǎng)問(wèn)數據字段
while ($row =& $res->fetchRow(DB_FETCHMODE_ASSOC)) {
echo $row[‘id‘] . "\n";
}
//獲取指定范圍的行數據
$from = 50;
$resPage = 10;
$to = $from + $resPage;
foreach (range($from, $to) as $rowNum) {
if (!$row =& $res->fetchRow($fetchmode, $rowNum)) {
break;
}
echo $row[0] . "\n";
}
//釋放資源
$res->free();
//通過(guò)getAll(),可以獲取整個(gè)查詢(xún)的結果集
$result = $db->getAll("select * from tablename");
//得到UPDATE/INSERT/DELETE等語(yǔ)句,所影響的行數
$db->query(‘DELETE * FROM clients‘);
echo ‘I have deleted ‘ . $db->affectedRows() . ‘ clients‘;
//close database connection
$db->disconnect();
?>
Prepare/Execute使用詳解
當要多次執行一組查詢(xún),只是有些參數不同時(shí)
INSERT INTO tle_name(col1, col2) VALUES(‘val1’, val2);
INSERT INTO tle_name(col1, col2) VALUES(‘val3’, val4);
……
或者你的語(yǔ)句要符合多個(gè)不同語(yǔ)法的數據庫時(shí)db1: INSERT INTO tbl_name (col1, col2) VALUES (expr1, expr2)
db2: INSERT INTO tbl_name SET col1=expr1, col2=expr2
可以使用prepare/execute語(yǔ)句,以提供更好的兼容性和可擴展性能
使用prepare/execute語(yǔ)句,要分2個(gè)步驟
1. 用prepare()來(lái)準備SQL語(yǔ)句:
假設你有一個(gè)類(lèi)似于這樣的SQL語(yǔ)句
SELECT surname, name, age
FROM person
WHERE name = ‘name_to_find‘ AND age < age_limit
使用prepare()時(shí),你可以這樣來(lái)寫(xiě):
SELECT surname, name, age
FROM person
WHERE name = ? AND age < ?
其中的類(lèi)似于JSP或其它語(yǔ)言中的參數變量,類(lèi)似的還有:
(推薦)
標準的用來(lái)代替數字(或字符)型變量的參數,它可以自動(dòng)地eacape或根據當前的DBMS系統的需要,來(lái)quoted數據
!
stands for a scalar value and will inserted into the statement "as is"
&
請求一個(gè)已經(jīng)存在的文件,這個(gè)文件的內容將用于替換&,常用于保存二進(jìn)制文件或圖象內容到數據庫中
2.execute() 把變量傳遞給prepare的SQL語(yǔ)句,然后執行它,execute()需要2個(gè)參數,一個(gè)是prepare()調用時(shí)指定的變量,另一個(gè)就是要傳遞給的變量(可以用數組)
一個(gè)簡(jiǎn)單的例子
<?php
// 假設你已經(jīng)有一個(gè)有效的數據庫連接變量$db …
$sth = $db->prepare(‘INSERT INTO numbers (number) VALUES (?)‘);
$db->execute($sth, 1);
$db->execute($sth, 8);
?>
一個(gè)保存圖象到數據庫的例子
假設數據庫中有一個(gè)test表,它的結構如下:
CREATE TABLE `test` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(100) default NULL,
`image` blob,
`description` text,
`note` text,
PRIMARY KEY (`id`)
) TYPE=MyISAM
insert.php
<?php
require_once ‘DB.php‘;
$dsn = ‘mysql://username:password@localhost/test‘;
$options = array(
‘debug‘ => 2,
‘portability‘ => DB_PORTABILITY_ALL,
);
$db =& DB::connect($dsn, $options);
if (DB::isError($db)) {
die($db->getMessage());
}
$db->setFetchMode(DB_FETCHMODE_ASSOC);
$sth = $db->prepare("INSERT test(name, image) VALUES(?, &)");
$db->execute($sth, array(‘jxyuhua‘, ‘D://websamples//PEAR//Database//welcome.jpg‘));
if (DB :: isError($db)) {
die($db->getMessage());
}
//$res->free();
$db->disconnect();
?>
存入數據庫之后(注意內容大小的限制),你就可以再將內容取出來(lái)顯示了
顯示的例子
image.php
<?php
require_once ‘DB.php‘;
$dsn = ‘mysql://username:password@localhost/test‘;
$options = array(
‘debug‘ => 2,
‘portability‘ => DB_PORTABILITY_ALL,
);
$db =& DB::connect($dsn, $options);
if (DB::isError($db)) {
die($db->getMessage());
}
$db->setFetchMode(DB_FETCHMODE_ASSOC);
$res = $db->query("select image from test where name = ? order by name", $_REQUEST[‘name‘]);
if (DB :: isError($res)) {
die($res->getMessage());
}
while ($row = $res->fetchRow()) {
$data = $row[‘image‘];
}
header("Content-type: image/jpeg"); //如果是其它的圖象格式,如GIF,要做相應的更改image/gif
echo ($data);
$res->free();
$db->disconnect();
?>
DB允許你一次進(jìn)行一組數據庫操作,例如,你要一次性地插入/更新一批數據,
<?php
//假設數據庫已經(jīng)連接
$alldata = array(array(1, ‘one‘, ‘en‘),
array(2, ‘two‘, ‘to‘),
array(3, ‘three‘, ‘tre‘),
array(4, ‘four‘, ‘fire‘));
$sth = $db->prepare(‘INSERT INTO numbers VALUES (?, ?, ?)‘);
foreach ($alldata as $row) {
$db->execute($sth, $row);
}
?>
以上語(yǔ)句將執行等效于下面的SQL語(yǔ)句功能:
INSERT INTO numbers VALUES (‘1‘, ‘one‘, ‘en‘)
INSERT INTO numbers VALUES (‘2‘, ‘two‘, ‘to‘)
INSERT INTO numbers VALUES (‘3‘, ‘three‘, ‘tre‘)
INSERT INTO numbers VALUES (‘4‘, ‘four‘, ‘fire‘)
如果你想更省事一點(diǎn),可以使用executeMultiple()
<?php
//假設數據庫已經(jīng)連接
$alldata = array(array(1, ‘one‘, ‘en‘),
array(2, ‘two‘, ‘to‘),
array(3, ‘three‘, ‘tre‘),
array(4, ‘four‘, ‘fire‘));
$sth = $db->prepare(‘INSERT INTO numbers VALUES (?, ?, ?)‘);
$db->executeMultiple($sth, $alldata);
?>
有沒(méi)有這樣的經(jīng)歷,當你在一個(gè)表中加了(或刪除)一些字段之后,你原來(lái)的SQL語(yǔ)句就必須要重新寫(xiě)過(guò),這樣是不是很煩人?
例如,你有一個(gè)user表,它有3個(gè)字段(id, name, country),你以前的INSERT/UPDATE語(yǔ)句:
INSERT INTO user (id, name, country) VALUES (?, ?, ?)
UPDATE user SET id=?, name=?, country=? WHERE ...
當你增加了一個(gè)字段(假設是birthday)之后,你就必須重新你以前的INSERT/UPDATE語(yǔ)句,而這很有可能會(huì )導至BUG的出現(假設你漏改了某些地方).
現在讓我們來(lái)看看怎樣用autoPrepare()/autoExecute()來(lái)解決這個(gè)問(wèn)題
1. autoPrepare()
用autoPrepare(),你不必列出INSERT/UPDATE的詳細語(yǔ)句,而只要指定它的基本信息
resource autoPrepare (string $table, array $table_fields, integer $mode = DB_AUTOQUERY_INSERT [, string $where = FALSE])
$table 表名
$table_fields 要進(jìn)行操作的字段名列表(數組類(lèi)型)
$mode (DB_AUTOQUERY_INSERT || DB_AUTOQUERY_UPDATE)
$where WHERE語(yǔ)句,用于過(guò)濾數據
<?php
// 假設你已經(jīng)有一個(gè)有效的數據庫連接變量$db …
$table_name = ‘user‘;
$table_fields = array(‘id‘, ‘name‘, ‘country‘);
$sth = $db->autoPrepare($table_name, $table_fields,
DB_AUTOQUERY_INSERT);
if (DB::isError($sth)) {
die($sth->getMessage());
}
$table_values = array(1, ‘Fabien‘, ‘France‘);
$res =& $db->execute($sth, $table_values);
if (DB::isError($res)) {
die($res->getMessage());
}
?>
在這個(gè)例子中,autoPrepare()會(huì )把它自動(dòng)翻譯成
INSERT INTO user (id, name, country) VALUES (?, ?, ?)
然后再自動(dòng)調用prepare()
注意:如果你使用DB_AUTOQUERY_UPDATE, 記得指定$where條件,否則將更新所有的數據.
2.autoExecute()
autoExecute()是autoPrepare()和execute()的混合體,它可以方便地執行INSERT/UPDATE
DB_Result autoExecute (string $table, array $fields_values [, integer $mode = DB_AUTOQUERY_INSERT [, string $where = FALSE]])
$table 表名
$table_fields 要進(jìn)行操作的字段名列表(數組類(lèi)型)
$mode (DB_AUTOQUERY_INSERT || DB_AUTOQUERY_UPDATE)
$where WHERE語(yǔ)句,用于過(guò)濾數據
<?php
// 假設你已經(jīng)有一個(gè)有效的數據庫連接變量$db …
$table_name = ‘user‘;
$fields_values = array(
‘id‘ => 1,
‘name‘ => ‘Fabien‘,
‘country‘ => ‘France‘
);
$res = $db->autoExecute($table_name, $fields_values,
DB_AUTOQUERY_INSERT);
if (DB::isError($res)) {
die($res->getMessage());
}
?>
它執行等效于下面的語(yǔ)句
INSERT INTO user (id, name, country) VALUES (1, ‘Fabien‘, ‘France‘)
是不是很方便簡(jiǎn)直帥呆了!
注意:如果你使用DB_AUTOQUERY_UPDATE, 記得指定$where條件,否則將更新所有的數據.