search
HomeBackend DevelopmentPHP ProblemDetailed introduction to PHP DBA extension

This article will introduce you to the DBA extension of PHP in detail. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

Detailed introduction to PHP DBA extension

Extended DBA learning in PHP

The DBA we are talking about today is not the traditional database administrator DBA, but a Buckley style in PHP Database extensions. The Buckley style database is actually what we often call a K/V database in the form of key-value pairs. Just like memcached or redis, which we usually use a lot, only one key corresponds to one value, but memcached mainly stores them in memory, while DBA extension stores data in files, just like a simple key Same as SQLite in value pair form.

The database types used by DBA extensions are basically open source, and deployment and release are very simple. It is just a db file, so it is very similar to SQLite. But the disadvantage is that it will load the database file into the memory at once. We cannot make the database too large, otherwise it will burst the memory. The DBA database is always together with the program, so it does not have network-related interfaces. We generally only use this kind of database locally in the code.

When installing, we need to add the --enable-dba=shared configuration during compilation, and then add an --enable-XXXX configuration. XXXX refers to the Buckley style database we want to use. Types, the more common ones include dbm, ndbm, gdbm, db2, etc. Similarly, the operating system also needs to install these related software. For example, our system is installed with gdbm, which needs to be installed using yum install.

A simple example

First let’s look at the code to see how our DBA database is used.

// 打开一个数据库文件
$id = dba_open("/tmp/test.db", "n", "gdbm");
//$id = dba_popen("/tmp/test1.db", "c", "gdbm");

// 添加或替换一个内容
dba_replace("key1", "This is an example!", $id);

// 如果内容存在
if(dba_exists("key1", $id)){
    // 读取内容
    echo dba_fetch("key1", $id), PHP_EOL;
    // This is an example!
}

dba_close($id);

First, use dba_open() to open a database file, the first parameter is the path of the database file, the second parameter is the opening method, including r, w, c, n, r means read-only, w means read-write, c means create plus read-write, n means if not It is created and can be read and written. The third parameter is the specified database type. Only the gdbm library is installed in our system, so we use gdbm as the parameter. Like mysql, we can also use dba_popen() to open a persistent link to a data file.

dba_replace() function is to add or replace a piece of data. If the data does not exist, add a new one. If the data exists, replace the value of the corresponding key. The first parameter is key, and the second parameter is the value of the data.

dba_exists() is to determine whether the specified key exists. If it exists, we will obtain the data specified by the key through dba_fetch() in this if.

dba_close() is just like other data operation handles, it closes the database connection handle.

Add, traverse, and delete data

In the above example, we use dba_replace() to add data. In fact, there are special functions for regular data addition.

// 添加数据
dba_insert("key2","This is key2!", $id);
dba_insert("key3","This is key3!", $id);
dba_insert("key4","This is key4!", $id);
dba_insert("key5","This is key5!", $id);
dba_insert("key6","This is key6!", $id);

// 获取第一个 key
$key = dba_firstkey($id);

$handle_later = [];
while ($key !== false) {
    if (true) {
        // 将 key 保存到数组中
        $handle_later[] = $key;
    }
    // 获取下一个 key
    $key = dba_nextkey($id);
}

// 遍历 key 数组,打印数据库中的全部内容
foreach ($handle_later as $val) {
    echo dba_fetch($val, $id), PHP_EOL;
    dba_delete($val, $id); // 删除key对应的内容
}
// This is key4!
// This is key2!
// This is key3!
// This is an example!
// This is key5!
// This is key6!

dba_insert() is to insert data. It will not replace the existing key data. If it is to insert the existing key information, it will return false.

dba_firstkey() is used to get the first key, dba_nextkey() is used to get the next key. Through these two functions, we can get all the key information in the entire database, and then we can These keys are used to traverse everything in the entire database.

dba_delete() deletes a piece of data based on the key.

Optimization and synchronization database

Even if it is mysql, after long-term use, we also need to do some sorting and optimization work, such as letting mysql automatically defragment files, organize indexes, etc., it uses The SQL statement is: optimize table name. In the same way, DBA extension also provides us with such a function.

// 优化数据库
var_dump(dba_optimize($id)); // bool(true)

In addition, just like the cache of mysql, the DBA will also cache when operating data. At this time, we can use a function to force the data in the cache to be flushed into the hard disk file.

// 同步数据库
var_dump(dba_sync($id)); // bool(true)

Currently open database list

We can use a function to see which data connections are currently open, because DBA is a simple file-based database, so we can open it in a piece of code Multiple data connections.

// 获取当前打开的数据库列表
var_dump(dba_list());
// array(1) {
//     [4]=>
//     string(12) "/tmp/test.db"
//   }

Database types supported by the system

Finally, let’s look at a supported function, which can return the database types currently supported by our database.

// 当前支持的数据库类型
var_dump(dba_handlers(true));
// array(5) {
//     ["gdbm"]=>
//     string(58) "GDBM version 1.18. 21/08/2018 (built May 11 2019 01:10:11)"
//     ["cdb"]=>
//     string(53) "0.75, $Id: 841505a20a8c9c8e35cac5b5dc3d5cf2fe917478 $"
//     ["cdb_make"]=>
//     string(53) "0.75, $Id: 95b1c2518144e0151afa6b2b8c7bf31bf1f037ed $"
//     ["inifile"]=>
//     string(52) "1.0, $Id: 42cb3bb7617b5744add2ab117b45b3a1e37e7175 $"
//     ["flatfile"]=>
//     string(52) "1.0, $Id: 410f3405266f41bafffc8993929b8830b761436b $"
//   }

var_dump(dba_handlers(false));
// array(5) {
//     [0]=>
//     string(4) "gdbm"
//     [1]=>
//     string(3) "cdb"
//     [2]=>
//     string(8) "cdb_make"
//     [3]=>
//     string(7) "inifile"
//     [4]=>
//     string(8) "flatfile"
//   }

dba_handlers() has a Boolean parameter. From the code, we can see that the function of this parameter is the detailed level of the returned information.

Summary

What we introduced today is a very simple set of database extension components. Its functions are just these. In daily production environments, there are not many actual application scenarios. We can use PHP file serialization to save simple key-value pairs, while caching will mostly use tools such as memcached, so you can learn about it.

Test code:

https://github.com/zhangyue0503/dev-blog/blob/master/php/202008/PHP%E7%9A%84DBA%E6%89%A9%E5%B1%95%E5%AD%A6%E4%B9%A0.md

Recommended learning: php video tutorial

The above is the detailed content of Detailed introduction to PHP DBA extension. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
ACID vs BASE Database: Differences and when to use each.ACID vs BASE Database: Differences and when to use each.Mar 26, 2025 pm 04:19 PM

The article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and

PHP Secure File Uploads: Preventing file-related vulnerabilities.PHP Secure File Uploads: Preventing file-related vulnerabilities.Mar 26, 2025 pm 04:18 PM

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

PHP Input Validation: Best practices.PHP Input Validation: Best practices.Mar 26, 2025 pm 04:17 PM

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

PHP API Rate Limiting: Implementation strategies.PHP API Rate Limiting: Implementation strategies.Mar 26, 2025 pm 04:16 PM

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

PHP Password Hashing: password_hash and password_verify.PHP Password Hashing: password_hash and password_verify.Mar 26, 2025 pm 04:15 PM

The article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur

OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.Mar 26, 2025 pm 04:13 PM

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

PHP XSS Prevention: How to protect against XSS.PHP XSS Prevention: How to protect against XSS.Mar 26, 2025 pm 04:12 PM

The article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.

PHP Interface vs Abstract Class: When to use each.PHP Interface vs Abstract Class: When to use each.Mar 26, 2025 pm 04:11 PM

The article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor