The mysqli_result::fetch_assoc() method is a member method of the mysqli_result class. It is used to return the next row of data in the query result set as an associative array. The key of this array is the name of the column in the database table, and the value is the value of the corresponding column.
This method returns the following possible values:
On success : Returns an associative array of a row of data.
When there is no more data : return null .
First, you need to connect to the MySQL database and execute a query. Then, you can use the mysqli_result::fetch_assoc() method to get the result set line by line. Here is a basic example:
<?php
// Create a database connection
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test_db";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check if the connection is successful
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Execute a query
$sql = "SELECT id, name, email FROM users";
$result = $conn->query($sql);
// Check whether the query is successful
if ($result->num_rows > 0) {
// use fetch_assoc() Get results
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " . $row["email"]. "<br>";
}
} else {
echo "0 results";
}
// Close the connection
$conn->close();
?>
Database connection : First, we use new mysqli() to create a database connection object and check whether the connection is successful.
Execute the query : Then, we execute an SQL query through the query() method to query the id , name and email fields in the users table.
Get the result : The $result->fetch_assoc() method gets the data from the result set line by line and returns an associative array. In this array, the key of the array is the column name (such as id , name , email ) in the database table, and the value is the corresponding column value.
Easy to use : By associating arrays, you can access data directly using column names without remembering the index of the column.
Flexibility : You can dynamically obtain data based on column names, which is especially suitable for scenarios that require multiple queries.
Strong adaptability : When the column order of the query changes, it will not affect the correctness of the code, because you access the data through the column names.
If you use a URL in your code and want to replace its domain name with m66.net , you can use PHP's str_replace() function. For example: