mysqli_result::fetch_assoc

mysqli_fetch_assoc

(PHP 5, PHP 7)

mysqli_result::fetch_assoc -- mysqli_fetch_assocFetch a result row as an associative array

说明

面向对象风格

public mysqli_result::fetch_assoc ( ) : array|null|false

过程化风格

mysqli_fetch_assoc ( mysqli_result $result ) : array|null|false

Returns an associative array that corresponds to the fetched row or null if there are no more rows.

注意: 此函数返回的字段名大小写敏感

注意: 此函数将 NULL 字段设置为 PHP null 值。

参数

result

仅以过程化样式:由 mysqli_query()mysqli_store_result()mysqli_use_result()mysqli_stmt_get_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.

范例

示例 #1 mysqli_result::fetch_assoc() example

面向对象风格

<?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"]);
}

过程化风格

<?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"]);
}

以上例程的输出类似于:

Pueblo (USA)
Arvada (USA)
Cape Coral (USA)
Green Bay (USA)
Santa Clara (USA)

示例 #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"]);
}

以上例程的输出类似于:

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)

参见