The mysql_fetch_array function takes a row from the result set as an array, and returns the array containing both association and index by default:
$result = mysql_query("SELECT * FROM users");
while ($row = mysql_fetch_array($result)) {
print_r($row);
}
Here $row is a record obtained in each loop, and the type is an array.
When you get a record from mysql_fetch_array , you usually use foreach to iterate through all fields of this data:
while ($row = mysql_fetch_array($result)) {
foreach ($row as $key => $value) {
echo "$key => $value<br>";
}
}
This is correct, because $row itself is an array.
Note that mysql_fetch_array returns a single record, and cannot directly use foreach for query result resources:
foreach ($result as $row) {
// Wrong usage,$resultIt's a resource,Not an array
}
This writing method is wrong and will lead to an error.
If you want to use foreach to traverse all records, the common practice is to read all the results into an array first, and then traverse:
$rows = [];
while ($row = mysql_fetch_array($result)) {
$rows[] = $row;
}
foreach ($rows as $record) {
// Process each record
echo $record['username'] . "<br>";
}
This way, you can easily handle all records in foreach .
The array returned by mysql_fetch_array by default has both numerical indexes and associated indexes, resulting in data redundancy. It is recommended to only get associative arrays:
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
// $rowContains only associative arrays
}
In this way, the array is simpler and the foreach traversal is more convenient.
<?php
// Connect to the database
$link = mysql_connect("gitbox.net", "username", "password");
mysql_select_db("testdb", $link);
// Query data
$result = mysql_query("SELECT id, username, email FROM users");
// Read all data
$rows = [];
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$rows[] = $row;
}
// useforeachIterate through all records
foreach ($rows as $record) {
echo "userID: " . $record['id'] . "<br>";
echo "user名: " . $record['username'] . "<br>";
echo "Mail: " . $record['email'] . "<br><hr>";
}
// Close the connection
mysql_close($link);
?>