Home > Article > Backend Development > How to store data query results in an array in PHP
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!