Home Backend Development PHP Problem How to query a database using PHP and store the results as a 2D array

How to query a database using PHP and store the results as a 2D array

Apr 27, 2023 am 09:05 AM

In PHP, we usually use SQL statements to query data in the database, and the result is often a two-dimensional array, that is, an array containing multiple records. This article will introduce how to use PHP language to query the database and store the results as a two-dimensional array.

1. Establish a database connection

Before querying the database, you first need to establish a database connection. This can be easily accomplished using PHP's built-in mysqli or PDO extensions. The following is a sample code for establishing a connection using mysqli extension:

// 连接数据库
$host = 'localhost';
$user = 'root';
$password = '';
$dbname = 'test';
$conn = new mysqli($host, $user, $password, $dbname);
// 检查连接是否成功
if ($conn->connect_errno) {
    die('连接失败: ' . $conn->connect_error);
}
Copy after login

2. Execute SQL query statement

After completing the database connection, we need to execute SQL query statement to obtain data. The query statement can be any legal SQL statement. For example, the SELECT statement can be used to obtain the value of a specific field from the database. The following is an example:

//执行查询并存储结果
$sql = "SELECT id, name, age FROM users";
$result = $conn->query($sql);
//检查结果是否为空
if ($result->num_rows > 0) {
    // 存储结果为二维数组
    $data = array();
    while ($row = $result->fetch_assoc()) {
        $data[] = $row;
    }
}
Copy after login

In the above code, we use the mysqli extended query method to execute the SQL query statement. After the query is successful, we use the num_rows method to check whether the result is empty. If the result is not empty, use the fetch_assoc method to store each row of data into an associative array, and add the array to the $data array. Finally, all data is stored in the $data array. So far, we have successfully stored the query results into a two-dimensional array.

3. Use the query results

Once the query results are stored as a two-dimensional array, we can use PHP language to operate on it. For example, you can output each record by looping through the array:

// 遍历数组并输出每条记录
foreach ($data as $row) {
    echo $row['id'] . "\t" . $row['name'] . "\t" . $row['age'] . "\n";
}
Copy after login

In the above code, we use a foreach loop to traverse the $data array and output the value of the id, name, and age fields of each record, where " \t" represents a tab character, and "\n" represents a newline character.

4. Close the database connection

After using the database, we need to close the database connection to release resources and ensure security. The following is an example:

// 关闭连接
$conn->close();
Copy after login

In the above code, we use the close method of the mysqli extension to close the database connection.

Summary

Querying the database and storing the results as a two-dimensional array in PHP is very simple. You only need to establish a database connection, execute the SQL query statement, store the results as a two-dimensional array, and use the query The result is enough. If you are using other database extensions, such as the PDO extension, it is also very simple to implement similar operations.

The above is the detailed content of How to query a database using PHP and store the results as a 2D array. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

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 8 JIT (Just-In-Time) Compilation: How it improves performance. PHP 8 JIT (Just-In-Time) Compilation: How it improves performance. Mar 25, 2025 am 10:37 AM

PHP 8's JIT compilation enhances performance by compiling frequently executed code into machine code, benefiting applications with heavy computations and reducing execution times.

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 Encryption: Symmetric vs. asymmetric encryption. PHP Encryption: Symmetric vs. asymmetric encryption. Mar 25, 2025 pm 03:12 PM

The article discusses symmetric and asymmetric encryption in PHP, comparing their suitability, performance, and security differences. Symmetric encryption is faster and suited for bulk data, while asymmetric is used for secure key exchange.

PHP Authentication & Authorization: Secure implementation. PHP Authentication & Authorization: Secure implementation. Mar 25, 2025 pm 03:06 PM

The article discusses implementing robust authentication and authorization in PHP to prevent unauthorized access, detailing best practices and recommending security-enhancing tools.

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 CSRF Protection: How to prevent CSRF attacks. PHP CSRF Protection: How to prevent CSRF attacks. Mar 25, 2025 pm 03:05 PM

The article discusses strategies to prevent CSRF attacks in PHP, including using CSRF tokens, Same-Site cookies, and proper session management.

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.

See all articles