search
HomeBackend DevelopmentPHP ProblemHow to convert query results into array in php

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!

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.