In PHP development, interacting with a database is a common and essential task. Particularly when executing database queries, we often need to store the query results in an array for further processing and display.
PHP provides various methods for handling query results, and one of the most commonly used is the “mysqli_fetch_assoc” function. This function retrieves a row from the result set of a database query and returns it as an associative array, allowing us to directly access the data by field names.
Here’s a simple example demonstrating how to use the “mysqli_fetch_assoc” function to fetch a row from a database query result:
<?php // Connect to the database $mysqli = new mysqli("localhost", "username", "password", "database"); // Check if the connection is successful if ($mysqli->connect_errno) { echo "Failed to connect to the database: " . $mysqli->connect_error; exit(); } // Execute the SELECT query $result = $mysqli->query("SELECT * FROM users"); // Check if any data is returned if ($result->num_rows > 0) { // Use mysqli_fetch_assoc to fetch a row $row = mysqli_fetch_assoc($result); // Output the associative array values echo "ID: " . $row['id'] . "<br>"; echo "Name: " . $row['name'] . "<br>"; echo "Age: " . $row['age'] . "<br>"; } else { echo "No data found."; } // Close the database connection $mysqli->close(); ?>
In the above code, we first use “new mysqli” to connect to the database and check if the connection was successful. Then, we execute a simple SELECT query and store the result in the “$result” variable. Next, we use the “mysqli_fetch_assoc” function to fetch one row of data from the result set, and access the field values through the associative array, finally displaying them on the web page.
It’s important to note that the “mysqli_fetch_assoc” function returns one row of data each time it’s called. To fetch multiple rows, you can loop and call the function repeatedly. For example:
<?php // Fetch multiple rows while ($row = mysqli_fetch_assoc($result)) { echo "ID: " . $row['id'] . "<br>"; echo "Name: " . $row['name'] . "<br>"; echo "Age: " . $row['age'] . "<br><br>"; } ?>
In this way, you can iterate through each row of the query result and process them as needed.
With the “mysqli_fetch_assoc” function, PHP developers can easily retrieve a row of data from the database result set as an associative array and access the data by field name. This method not only improves code readability but also simplifies the handling of database query results.
We hope the example in this article helps you better understand and apply the “mysqli_fetch_assoc” function in your development work!