Today I want to share with you how to convert query results into an array in PHP. In web development, we often need to get data from a database and display it on a web page. Using PHP and MySQL is a very common choice. When we execute a query and get the results, we usually get a result set object, which contains multiple records. In order to facilitate processing and manipulation of this data, we can convert it into an array.
In PHP, we can use the mysqli extension and PDO extension to connect to the MySQL database. Both extensions provide methods to convert query results into arrays. In this article, I will introduce each of these two methods.
1. Use the mysqli extension to convert query results into an array
mysqli is the recommended MySQL database extension for PHP 5 and above. It provides a set of object-oriented interfaces, including connecting to MySQL database, executing SQL queries, processing results, etc. Among them, the mysqli_result class is an object representing the result set. We can convert the result set into an array by calling the fetch_array method in the mysqli_result class.
The fetch_array method accepts a parameter indicating the type of array to be returned. By default, it returns an array containing the number and associated index. We can specify the array type to be returned by using the MYSQLI_ASSOC, MYSQLI_NUM or MYSQLI_BOTH constants in the passed parameters.
The following is an example:
// 连接数据库 $conn = new mysqli('localhost', 'username', 'password', 'database'); // 执行查询,获取结果集对象 $result = $conn->query('SELECT * FROM users'); // 将结果集转换为数组 $rows = $result->fetch_array(MYSQLI_ASSOC); // 输出数组 print_r($rows);
This code will output the first row of data in the query results. If you want to output all rows of data, you can use a while loop.
// 连接数据库 $conn = new mysqli('localhost', 'username', 'password', 'database'); // 执行查询,获取结果集对象 $result = $conn->query('SELECT * FROM users'); // 遍历结果集,将每行数据转换为数组并输出 while ($row = $result->fetch_array(MYSQLI_ASSOC)) { print_r($row); }
2. Use the PDO extension to convert the query results into an array
PDO is a database extension provided in PHP 5.1 and above. It supports a variety of databases, including MySQL, PostgreSQL, and SQLite , Oracle, etc. The PDO extension provides a PDOStatement object to represent the result set after executing the SQL query. We can use the fetch method in the object to convert the result set into an array.
The fetch method also accepts a parameter indicating the type of array to be returned. By default, it returns an array containing the number and associated index. We can specify the array type to be returned by using the PDO::FETCH_ASSOC, PDO::FETCH_NUM or PDO::FETCH_BOTH constants in the passed parameters.
The following is an example:
// 连接数据库 $dsn = 'mysql:host=localhost;dbname=database'; $username = 'username'; $password = 'password'; $conn = new PDO($dsn, $username, $password); // 执行查询,获取 PDOStatement 对象 $stmt = $conn->query('SELECT * FROM users'); // 将结果集转换为数组 $rows = $stmt->fetch(PDO::FETCH_ASSOC); // 输出数组 print_r($rows);
Similarly, if you want to output all rows of data, you can use a while loop:
// 连接数据库 $dsn = 'mysql:host=localhost;dbname=database'; $username = 'username'; $password = 'password'; $conn = new PDO($dsn, $username, $password); // 执行查询,获取 PDOStatement 对象 $stmt = $conn->query('SELECT * FROM users'); // 遍历结果集,将每行数据转换为数组并输出 while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { print_r($row); }
Summary
Here, We've learned how to use mysqli and the PDO extension to convert query results into an array. In actual development, we usually use frameworks or ORMs (such as Laravel, Doctrine, etc.) to simplify this process. But understanding this basic implementation is very important for us to understand the underlying principles of web development. I hope this article can be helpful to readers.
The above is the detailed content of How to convert query results into array in php. For more information, please follow other related articles on the PHP Chinese website!

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

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.

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.

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 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

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.

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

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


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

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

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

SublimeText3 English version
Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.