1. 簡介這是一部指導我們如何使用Pear DB擴展。Pear DB,提供這樣一系列的類:
以下是strp by step示例:
存放Pear的目錄:
# cd /usr/local/lib
用“phpfi“口令登錄:
# cvs -d :pserver:[email protected]:/repository login
用以下命令得到所有的pear文件,同時也可以用來更新已經下載的文件。其他的參數有:"today", "last month",等。我推薦用"last week"參數,因為一般bugs的提交和修改都是每周一次。
# cvs -d :pserver:[email protected]:/repository export -D "last week" php4/pear
編輯php.ini文件加上下面一段在include_path處: /usr/local/lib/php4/pear 如果沒有修改的權限,可以通過這條語句在代碼中實現: ini_set('include_path', 'path_to_pear');
獲得PHP CVS的完全文檔
注意Pear DB必需PHP版本4.0.4以上,而在Pear中的一些其他包如:XML Parser of the pear installer script需要PHP4.0.5以上版本。
3. 使用Pear DB
3.1 連接,斷開數據庫
<?php
// The pear base directory must be in your include_path
require_once
'DB.php'
;
$user
=
'foo'
;
$pass
=
'bar'
;
$host
=
'localhost'
;
$db_name
=
'clients_db'
;
// Data Source Name: This is the universal connection string
$dsn
=
"mysql://$user:$pass@$host/$db_name"
;
// DB::connect will return a Pear DB object on success
// or a Pear DB Error object on error
// You can also set to TRUE the second param
// if you want a persistent connection:
// $db = DB::connect($dsn, true);
$db
=
DB
::
connect
(
$dsn
);
// With DB::isError you can differentiate between an error or
// a valid connection.
if (
DB
::
isError
(
$db
)) {
die (
$db
->
getMessage
());
}
....
// You can disconnect from the database with:
$db
->
disconnect
();
?>
數據源(上例中的$dsn 參數)有以下允許的格式:(從Pear/DB.php的parseDSN方法復制而來)
* phptype: Database backend used in PHP (mysql, odbc etc.)
* dbsyntax: Database used with regards to SQL syntax etc.
* protocol: Communication protocol to use (tcp, unix etc.)
* hostspec: Host specification (hostname[:port])
* database: Database to use on the DBMS server
* username: User name for login
* password: Password for login
*
* The format of the supplied DSN is in its fullest form:
*
* phptype(dbsyntax)://username:password@protocol+hostspec/database
*
* Most variations are allowed:
*
* phptype://username:password@protocol+hostspec:110//usr/db_file.db
* phptype://username:password@hostspec/database_name
* phptype://username:password@hostspec
* phptype://username@hostspec
* phptype://hostspec/database
* phptype://hostspec
* phptype(dbsyntax)
* phptype
現在支持的數據庫有 (在 phptype DSN 部分):
mysql -> MySQL
pgsql -> PostgreSQL
ibase -> InterBase
msql -> Mini SQL
mssql -> Microsoft SQL Server
oci8 -> Oracle 7/8/8i
odbc -> ODBC (Open Database Connectivity)
sybase -> SyBase
ifx -> Informix
fbsql -> FrontBase
注意並不是所有數據庫特征都支持,可以從
3.2 執行數據庫
<?php
// Once you have a valid DB object
...
$sql
=
"select * from clients"
;
// If the query is a "SELECT", $db->query will return
// a DB Result object on success.
// Else it simply will return a DB_OK
// On failure it will return a DB Error object.
$result
=
$db
->
query
(
$sql
);
// Always check that $result is not an error
if (
DB
::
isError
(
$result
)) {
die (
$result
->
getMessage
());
}
....
?>
3.3 獲得select的數據