In PHP, we often need to query data from the database and store the query results in an array for subsequent processing. Next, I will introduce to you how to store data query results in an array in PHP.
First, we need to connect to the database. Using PHP's built-in mysqli or PDO library, the connection operation can be completed conveniently and quickly. Taking mysqli as an example, the sample code is as follows:
$mysqli = new mysqli('localhost', 'username', 'password', 'database'); if ($mysqli->connect_errno) { echo "Failed to connect to MySQL: " . $mysqli->connect_error; exit(); }
In the above code, we first instantiate a mysqli object and pass the parameters required for the connection. If the connection fails, we will print an error message and end the script.
Next, we need to construct the query statement and run the query. The sample code is as follows:
$query = "SELECT * FROM my_table"; $result = $mysqli->query($query); if ($result === false) { echo "Query error: " . $mysqli->error; exit(); }
In the above code, we define a query string $query, which simply queries all records of the table my_table. Next, we run the query using the query method of the mysqli object and store the results in the variable $result. If the query fails, we will print an error message and end the script.
Now, we have successfully queried the data from the database. Next, we need to store the query results in an array. The sample code is as follows:
$rows = array(); while ($row = $result->fetch_assoc()) { $rows[] = $row; }
In the above code, we instantiate an empty array $rows and use a while loop to traverse the query results. In each loop, we call the fetch_assoc method of the mysqli_result object, store all the data for the current row in the associative array $row, and add $row to the end of the array $rows. In this way, when the loop ends, $rows will contain all records in the query results.
Now, we have stored the query results in an array. For smaller data sets, using arrays directly is sufficient. But for larger data sets, we may need paging or other methods of data processing to improve the efficiency of the code. In addition, when using arrays to store query results, we also need to pay attention to data types and data security to avoid security issues such as SQL injection.
In short, storing query results in an array is a very common operation in PHP development. Mastering this skill allows us to process large amounts of data more efficiently and operate the database more flexibly.
The above is the detailed content of How to store data query results in an array in PHP. For more information, please follow other related articles on the PHP Chinese website!

This article explores efficient PHP array deduplication. It compares built-in functions like array_unique() with custom hashmap approaches, highlighting performance trade-offs based on array size and data type. The optimal method depends on profili

This article analyzes PHP array deduplication, highlighting performance bottlenecks of naive approaches (O(n²)). It explores efficient alternatives using array_unique() with custom functions, SplObjectStorage, and HashSet implementations, achieving

This article explores PHP array deduplication using key uniqueness. While not a direct duplicate removal method, leveraging key uniqueness allows for creating a new array with unique values by mapping values to keys, overwriting duplicates. This ap

This article details implementing message queues in PHP using RabbitMQ and Redis. It compares their architectures (AMQP vs. in-memory), features, and reliability mechanisms (confirmations, transactions, persistence). Best practices for design, error

This article examines current PHP coding standards and best practices, focusing on PSR recommendations (PSR-1, PSR-2, PSR-4, PSR-12). It emphasizes improving code readability and maintainability through consistent styling, meaningful naming, and eff

This article explores optimizing PHP array deduplication for large datasets. It examines techniques like array_unique(), array_flip(), SplObjectStorage, and pre-sorting, comparing their efficiency. For massive datasets, it suggests chunking, datab

This article details installing and troubleshooting PHP extensions, focusing on PECL. It covers installation steps (finding, downloading/compiling, enabling, restarting the server), troubleshooting techniques (checking logs, verifying installation,

This article explains PHP's Reflection API, enabling runtime inspection and manipulation of classes, methods, and properties. It details common use cases (documentation generation, ORMs, dependency injection) and cautions against performance overhea


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version
Visual web development tools

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

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
