CakeFest 2024: The Official CakePHP Conference

dba_open

(PHP 4, PHP 5, PHP 7, PHP 8)

dba_openAbrir una base de datos

Descripción

dba_open(
    string $path,
    string $mode,
    string $handler = ?,
    mixed $... = ?
): resource

dba_open() establece una instancia de una base de datos para path con mode usando handler.

Parámetros

path

Comúnmente una ruta normal de su sistema de ficheros.

mode

Es r para acceso de lectura, w para acceso de lectura/escritura de una base de datos existente, c para acceso de lectura/escritura y creación de una base de datos si no existe actualmente, y n para crear, truncar y acceso de lectura/escritura. La base de datos se crea en el modo BTree, los demás modos (como Hash o Queue) no están soportados.

Además se puede establecer el método de bloqueo de la base de datos con el siguiente carácter. Use l para bloquear la base de datos con un fichero .lck o d para bloquear el fichero de la base de datos mismo. Es importante que todas sus aplicaciones hagan esto de manera consistente.

Si quiere probar el acceso y no quiere esperar para el bloqueo puede añadir t como tercer carácter. Cuando está absolutamente seguro de que no se requiere el bloqueo de la base de datos, puede usar - en lugar de l o d. Cuando no se usar d, l o -, dba bloqueará el archivo de la base de datos como si lo estuviera con d.

Nota:

Sólo puede haber un escritor para el archivo de la base de datos. Cuando se usa dba en un servidor web y más de una solicitud requiere operaciones de escritura, sólo pueden hacerlo una tras otra. Tampoco está permitido la lectura durante la escritura. La extensión dba usa bloqueos para impedirlo. Véase la siguiente tabla:

Bloqueo de DBA
ya abierta mode = "rl" mode = "rlt" mode = "wl" mode = "wlt" mode = "rd" mode = "rdt" mode = "wd" mode = "wdt"
sin abrir 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: la segunda llamada tendrá éxito.
  • wait: la sedunda llamada esperará hasta que se llame a dba_close() la primera vez.
  • false: la segunda llamada devuelve false.
  • illegal: no se pueden mezclar los modificadores "l" y "d" con el parámetro mode.

handler

El nombre del gestor que será usado para acceder a path. Se le pasan todos los parámetros opcionales dados a dba_open() y puede actuar en su nombre.

Valores devueltos

Devuelve un gestor positivo en caso de éxito o false en caso de error.

Historial de cambios

Versión Descripción
4.3.0 Es posible abrir ficheros de bases de datos sobre conexiones de red. Sin embargo, en el caso en que se use una conexión de socket (como con http o ftp) la conexión se bloqueará en lugar del recurso en sí. Esto es importante para saber que en tales casos el bloqueo es ignorado simplemente en el recurso y se tienen que encontrar otras soluciones.

Ver también

add a note

User Contributed Notes 6 notes

up
1
doppelbauer at gmail dot com
17 years ago
Windows does not support locking the database. You may use $_ENV to determine the OS:

$locking = (stripos($_ENV['OS'],'windows') === false ? 'd' : 'l');
up
0
dracoirs at gmail dot com
13 years ago
Apache doesn't support Berkeley DB Btree, so you can't manipulate use db4 as the type of database if you want to do DBM authentication with Apache.

gdbm seemed to work fine though, even though it supposedly using Btree instead of hash. It makes you wonder why Apache would use hash for one dbmtype versus btree for another.

So since Apache and PHP don't have options to choose the method for the Berkeley DBs, you are out of luck.
up
0
mskala at ansuz dot sooke dot bc dot ca
15 years ago
As of GDBM version 1.8.3, GDBM's underlying open call uses non-blocking calls to flock() on systems that have flock(). As a result, calls with "rd" or "wd" locking modes will return error ("Can't be reader" or "Can't be writer") instead of waiting. Use "rl" or "wl" instead, to make PHP do its own locking external to GDBM.
up
0
xy ät affenkrieger.de
17 years ago
If you get some strange errors like
dba_open(): myDbFilename.db : Permission denied
than you are propably using PHP on a Windoze machine. You have to make sure that the following conditions are met:

1) Use an absolute path to your db file. Relative paths will cause problems with locking
2) Specify a locking mode - that's the second character of the mode-argument, or else opening a dba-file will cause several notices/warnings etc.

And a final, general note:
3) Always use the english PHP doc on this site - the translations are often old as hell and miss important informations

HTH, Nils.
up
-2
trohit at blue bottle dot com
16 years ago
Here's a simple example to use the dba_open function

<?php

$id
= dba_open("/tmp/test.db", "n", "gdbm");

if (!
$id) {
echo
"dba_open failed\n";
exit;
}

dba_replace("key", "This is an example!", $id);

if (
dba_exists("key", $id)) {
echo
dba_fetch("key", $id);
dba_delete("key", $id);
}

dba_close($id);
?>
up
-4
cbemerine at gmail dot com
14 years ago
Note the “c” create flag does not work if MySQL was built with the “cdb” DBA handler compile option which is common for many distros. By definition the cdb DBA handler is optimized for reading/writing and “no updates are allowed.”

<?php
$dbh
= dba_open( "./data2/productz", "c", "cdb") or die( "Couldn't open Database" );
?>

instead use

<?php
$dbh
= dba_open( "./data2/productz", "n", "cdb" ) or die( "Couldnt open Database" );
?>

generates this error message in the /var/log/apache2/error.log:
[Sun Sep 06 04:18:15 2009] [error] [client 192.168.1.125] PHP Warning: dba_open(./data2/productz,c) [<a href='function.dba-open'>function.dba-open</a>]: Driver initialization failed for handler: cdb: Update operations are not supported in /var/www/projects/testcdb-c.php on line 43

see user contributed comment under dba_handlers() to see which DBA handlers are supported by your build of MySQL and note about using “cdb” compiled DBA systems:

also see user contributed comment under dba_replace() about incompatibilities with cdb DBA handler compiled MySQL systems.
To Top