PHP 的 DBA(Database (dbm-style) Abstraction Layer) 可以接 Oracle Berkeley DB.
這邊有相容的 DB Layer 列表: PHP: Requirements - Manual
註: 此篇文章的範例使用 db4, 確定 PHP 5.3.3 以上可以正常執行, 不能執行的話, 可以換成 dbm 先測試看看. 🙂
Debian、Ubuntu Linux 安裝管理套件
- apt-get install db-util # 就可以有 db_dump、db_load、db_hotbackup、db_stat 等可以使用
PHP 的 DBA 基本操作 程式範例
下述的範例, dba_open() 可以於最上面打開, 於最下面 dba_close() 即可.
此範例內容於每個區塊都 open / close, 主要是要方便 copy 用, 只要拷貝此一區塊的程式, 就可以直接套用.
<?php define('DB_FILE', '/tmp/dbadata.db'); // 此檔案即為 DB 檔, 請隨意命名 if (!file_exists(DB_FILE)) { $dbh = dba_open(DB_FILE, 'n', 'db4'); dba_close($dbh); } $result = array('abc', 'def'); // 新增 $dbh = dba_open(DB_FILE, 'c', 'db4'); dba_replace('key1', serialize($result), $dbh); dba_replace('key2', serialize($result), $dbh); dba_close($dbh); // 抓取、確認 (修改模式也可以讀取 "c") $dbh = dba_open(DB_FILE, 'c', 'db4'); $data = dba_fetch('key1', $dbh); echo "key1\n"; print_r(unserialize($data)); $data = dba_fetch('key2', $dbh); echo "key2\n"; print_r(unserialize($data)); dba_close($dbh); // 修改 $dbh = dba_open(DB_FILE, 'c', 'db4'); dba_replace('key1', 'abc', $dbh); dba_close($dbh); // 抓取、確認 (讀取 "r") $dbh = dba_open(DB_FILE, 'r', 'db4'); $data = dba_fetch('key1', $dbh); echo "key1\n"; print_r($data); dba_close($dbh); // 刪除 $dbh = dba_open(DB_FILE, 'c', 'db4'); dba_delete('key2', $dbh); dba_close($dbh); // Dump all $dbh = dba_open(DB_FILE, 'r', 'db4'); $key = dba_firstkey($dbh); $i = 0; $list = array(); while ($key != NULL) { $list[$i][$key] = dba_fetch($key, $dbh); $key = dba_nextkey($dbh); $i++; } print_r($list); ?>