📅  最后修改于: 2023-12-03 14:44:31.193000             🧑  作者: Mango
One important feature of PHP for database interaction is the ability to retrieve data from a database using the MySQLi extension. Two commonly used functions for this purpose are mysqli_fetch_row()
and mysqli_fetch_assoc()
. Both functions are used to fetch data from a result set returned by a database query, but they have different ways of returning that data.
The mysqli_fetch_row()
function returns a numerical array that represents a single row of data from the result set. The array consists of elements that correspond to the columns selected in the query. The array index starts from 0.
Here is an example usage:
$result = mysqli_query($link, "SELECT * FROM mytable");
while ($row = mysqli_fetch_row($result)) {
printf ("%s (%s)\n", $row[0], $row[1]);
}
In the above example, $row[0]
and $row[1]
correspond to the first and second columns returned by the query.
The mysqli_fetch_assoc()
function, on the other hand, returns an associative array that represents a single row of data from the result set. The array consists of key-value pairs, where the keys correspond to the column names in the query and the values are the actual data from the row.
Here is an example usage:
$result = mysqli_query($link, "SELECT * FROM mytable");
while ($row = mysqli_fetch_assoc($result)) {
printf ("%s (%s)\n", $row["name"], $row["age"]);
}
In the above example, $row["name"]
and $row["age"]
correspond to the "name" and "age" columns returned by the query.
Both mysqli_fetch_row()
and mysqli_fetch_assoc()
are useful functions for retrieving data from a database in PHP. Developers can choose which function to use depending on their preference or the requirements of their application.