


How to query a database using PHP and store the results as a 2D array
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); }
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; } }
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"; }
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();
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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's JIT compilation enhances performance by compiling frequently executed code into machine code, benefiting applications with heavy computations and reducing execution times.

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.

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.

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

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

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

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.
