(PHP 5, PHP 7)
mysqli_result::fetch_assoc -- mysqli_fetch_assoc — Fetch a result row as an associative array
Object oriented style
Procedural style
Returns an associative array that corresponds to the fetched row or null
if there are no more rows.
Note: Field names returned by this function are case-sensitive.
Note: This function sets NULL fields to the PHP
null
value.
result
Procedural style only: A result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result().
Returns an associative array of values representing the fetched row in the result
set, where each key in the array represents the name of one of the result
set's columns or null
if there are no more rows in result set.
If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you either need to access the result with numeric indices by using mysqli_fetch_row() or add alias names.
Example #1 mysqli_result::fetch_assoc() example
Object oriented style
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$query = "SELECT Name, CountryCode FROM City ORDER BY ID DESC";
$result = $mysqli->query($query);
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
printf("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}
Procedural style
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect("localhost", "my_user", "my_password", "world");
$query = "SELECT Name, CountryCode FROM City ORDER BY ID DESC";
$result = mysqli_query($mysqli, $query);
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
printf("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}
The above examples will output something similar to:
Pueblo (USA) Arvada (USA) Cape Coral (USA) Green Bay (USA) Santa Clara (USA)
Example #2 Comparison of mysqli_result iterator and mysqli_result::fetch_assoc() usage
mysqli_result can be iterated using foreach. The result set will always be iterated from the first row, regardless of the current position.
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$query = 'SELECT Name, CountryCode FROM City ORDER BY ID DESC';
// Using iterators
$result = $mysqli->query($query);
foreach ($result as $row) {
printf("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}
echo "\n==================\n";
// Not using iterators
$result = $mysqli->query($query);
while ($row = $result->fetch_assoc()) {
printf("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}
The above example will output something similar to:
Pueblo (USA) Arvada (USA) Cape Coral (USA) Green Bay (USA) Santa Clara (USA) ================== Pueblo (USA) Arvada (USA) Cape Coral (USA) Green Bay (USA) Santa Clara (USA)