How to Use mysqli_fetch_assoc in PHP to Retrieve Query Results
This tutorial explains how to connect to a MySQL database using PHP's mysqli extension, execute queries, and retrieve results with mysqli_fetch_assoc, providing step-by-step code examples for connection, querying, and a complete script.
In PHP, database operations are a crucial part of development. Using the mysqli extension is a common method. This article introduces how to use the mysqli_fetch_assoc function to obtain query results.
1. Connect to Database
First, we need to use the mysqli_connect function to establish a connection to a MySQL database. Below is an example code:
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "myDB";
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}2. Query Database
Next, we can use the mysqli_query function to execute an SQL query.
Here is a query example:
$sql = "SELECT id, name, email FROM users";
$result = mysqli_query($conn, $sql);After executing the query, we can use mysqli_fetch_assoc to fetch each row of the result as an associative array. The function returns the next row on each call until all rows are retrieved.
while ($row = mysqli_fetch_assoc($result)) {
echo "ID: " . $row["id"] . ", Name: " . $row["name"] . ", Email: " . $row["email"] . "
";
}3. Full Example
Below is a complete example demonstrating how to use mysqli_fetch_assoc to fetch query results:
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "myDB";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT id, name, email FROM users";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "ID: " . $row["id"] . ", Name: " . $row["name"] . ", Email: " . $row["email"] . "
";
}
} else {
echo "0 results";
}
mysqli_close($conn);Note: The database name, credentials, and table structure in the example should be replaced with those of your actual environment.
Summary
This article introduced how to use the mysqli_fetch_assoc function to retrieve query results. By connecting to the database, executing a query, and iterating the result set with mysqli_fetch_assoc , developers can easily access data and improve development efficiency.
php8, I'm here
Scan the QR code to receive free learning materials
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.