PHP database operation skills: How to use the mysqli_fetch_assoc function to obtain query results
In PHP, database operations are a very important part of development. Using the mysqli extension library for database operations is one of the common methods. This article will introduce how to use the mysqli_fetch_assoc function to obtain query results.
$servername = "localhost"; $username = "root"; $password = "password"; $dbname = "myDB"; $conn = mysqli_connect($servername, $username, $password, $dbname); // 检查连接是否成功 if (!$conn) { die("连接失败: " . mysqli_connect_error()); }
$sql = "SELECT id, name, email FROM users"; $result = mysqli_query($conn, $sql);
After executing the query, we can use the mysqli_fetch_assoc function to get the results of each row, returned in the form of an associative array. Each call to this function will return the next row of data until all rows of data have been fetched.
while ($row = mysqli_fetch_assoc($result)) { echo "ID: " . $row["id"] . ", Name: " . $row["name"] . ", Email: " . $row["email"] . "<br>"; }
$servername = "localhost"; $username = "root"; $password = "password"; $dbname = "myDB"; $conn = mysqli_connect($servername, $username, $password, $dbname); if (!$conn) { die("连接失败: " . 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 结果"; } mysqli_close($conn);
It should be noted that the database and database in this example The table structure needs to be replaced according to the actual situation.
Summary:
This article introduces how to use the mysqli_fetch_assoc function to obtain query results. We can easily obtain data from the database by connecting to the database, executing query statements, and traversing the result set using the mysqli_fetch_assoc function. By properly using the mysqli_fetch_assoc function, we can operate the database more efficiently and improve development efficiency.
I hope this article can be of some help to PHP database operations. thanks for reading!
The above is the detailed content of PHP database operation skills: How to use the mysqli_fetch_assoc function to obtain query results. For more information, please follow other related articles on the PHP Chinese website!