php dba函数之dba_open()使用讲解

时间:2016-07-10
php dba_open()函数用于打开打开指定路径的dba数据库,本文章向大家讲解dba_open()函数的使用方法很基本使用实例,需要的朋友可以参考一下。

dba_open()介绍

语法:

resource dba_open ( string $path , string $mode [, string $handler [, mixed $... ]])

参数:

string $path :打开数据库所在的目录。

string $mode : 打开的模式。第一个字符位置,'r’:读的方式; 'w’:写的方式; 'c’:读写方式,如果数据库不存在,则创建; 'n’:创建,以读写方式;第二个字符位置,'l’:以锁定的方式,并生成一个.lck的文件; 'd’:锁定数据库自己。第三个字符位置:'t’:测试访问锁而且不想等待的时候,用此选项。

注意:对一个数据库文件,只能有一个人可以写操作。当dba数据库用在web服务或者多个需要写操作的时候,只能是一个接着一个,不能同时写,而且在写的时候,读也是不允许的。dba的扩展用锁来防止同时操作,请看下表:

DBA locking
already open mode = "rl" mode = "rlt" mode = "wl" mode = "wlt" mode = "rd" mode = "rdt" mode = "wd" mode = "wdt"
not open ok ok ok ok ok ok ok ok
mode = "rl" ok ok wait false illegal illegal illegal illegal
mode = "wl" wait false wait false illegal illegal illegal illegal
mode = "rd" illegal illegal illegal illegal ok ok wait false
mode = "wd" illegal illegal illegal illegal wait false wait false

介绍:

  • ok: the second call will be successfull. 第二次调用将会成功
  • wait: the second call waits until dba_close() is called for the first. 第二次调用会等待,直到调用dba_close() 时候
  • false: the second call returns false. 第二次调用会返回false
  • illegal: you must not mix "l" and "d" modifiers for mode parameter.'l' 和 'd'禁止混合使用在模式参数中

string $handler:使用的数据库

返回值:

成功返回handler, 失败返回 false

dba_open()实例

<?php
$data_file = '/tmp/users.db';
$total_length = 0;
if (! ($dbh = dba_open($data_file,'r','gdbm'))) {
    die("无法打开数据库$data_file");
}

$k = dba_firstkey($dbh);
while ($k) {
    $total_length += strlen(dba_fetch($k,$dbh));
    $k = dba_nextkey($dbh);
}

print "Total length of all passwords is $total_length characters.";

dba_close($dbh);
?>