mysqli_result::fetch_assoc
(PHP 5, PHP 7)
mysqli_result :: fetch_assoc -- mysqli_fetch_assoc — 将结果行作为关联数组提取
描述
面向对象的风格
array mysqli_result::fetch_assoc ( void )
程序风格
array mysqli_fetch_assoc ( mysqli_result $result )
返回与获取的行对应的关联数组,或者NULL
没有更多行。
注意:此函数返回的字段名称区分大小写。
注意:该函数将NULL字段设置为PHP
NULL
值。
参数
`result`
仅过程风格:由mysqli_query(),mysqli_store_result()或mysqli_use_result()返回的结果集标识符。
返回值
返回表示结果集中获取行的字符串的关联数组,其中数组中的每个键表示结果集的列之一或结果集中NULL
没有更多行。
如果结果的两列或多列具有相同的字段名称,则最后一列优先。要访问同名的其他列,您需要使用mysqli_fetch_row()或添加别名来访问带有数字索引的结果。
例子
Example#1面向对象的风格
<?php
$mysqli?=?new?mysqli("localhost",?"my_user",?"my_password",?"world");
/*?check?connection?*/
if?($mysqli->connect_errno)?{
????printf("Connect?failed:?%s\n",?$mysqli->connect_error);
????exit();
}
$query?=?"SELECT?Name,?CountryCode?FROM?City?ORDER?by?ID?DESC?LIMIT?50,5";
if?($result?=?$mysqli->query($query))?{
????/*?fetch?associative?array?*/
????while?($row?=?$result->fetch_assoc())?{
????????printf?("%s?(%s)\n",?$row["Name"],?$row["CountryCode"]);
????}
????/*?free?result?set?*/
????$result->free();
}
/*?close?connection?*/
$mysqli->close();
?>
示例#2程序风格
<?php
$link?=?mysqli_connect("localhost",?"my_user",?"my_password",?"world");
/*?check?connection?*/
if?(mysqli_connect_errno())?{
????printf("Connect?failed:?%s\n",?mysqli_connect_error());
????exit();
}
$query?=?"SELECT?Name,?CountryCode?FROM?City?ORDER?by?ID?DESC?LIMIT?50,5";
if?($result?=?mysqli_query($link,?$query))?{
????/*?fetch?associative?array?*/
????while?($row?=?mysqli_fetch_assoc($result))?{
????????printf?("%s?(%s)\n",?$row["Name"],?$row["CountryCode"]);
????}
????/*?free?result?set?*/
????mysqli_free_result($result);
}
/*?close?connection?*/
mysqli_close($link);
?>
上面的例子会输出:
Pueblo (USA)
Arvada (USA)
Cape Coral (USA)
Green Bay (USA)
Santa Clara (USA)
Example#3一个 比较迭代器用法的mysqli_result 例子
<?php
$c?=?mysqli_connect('127.0.0.1','user',?'pass');
//?Using?iterators?(support?was?added?with?PHP?5.4)
foreach?(?$c->query('SELECT?user,host?FROM?mysql.user')?as?$row?)?{
????printf("'%s'@'%s'\n",?$row['user'],?$row['host']);
}
echo?"\n==================\n";
//?Not?using?iterators
$result?=?$c->query('SELECT?user,host?FROM?mysql.user');
while?($row?=?$result->fetch_assoc())?{
????printf("'%s'@'%s'\n",?$row['user'],?$row['host']);
}
?>
上面的例子会输出类似于:
'root'@'192.168.1.1'
'root'@'127.0.0.1'
'dude'@'localhost'
'lebowski'@'localhost'
==================
'root'@'192.168.1.1'
'root'@'127.0.0.1'
'dude'@'localhost'
'lebowski'@'localhost'
本文档系腾讯云开发者社区成员共同维护,如有问题请联系 cloudcommunity@tencent.com