导航首页 » 技术教程 » PHP:MySQL函数mysql_fetch_assoc()的用法
PHP:MySQL函数mysql_fetch_assoc()的用法 172 2023-12-13   

mysql_fetch_assoc

(PHP 4 >= 4.0.3, PHP 5)

mysql_fetch_assoc — 从结果集中取得一行作为关联数组

Warning

本扩展自 PHP 5.5.0 起已废弃,并在将来会被移除。应使用 MySQLi 或 PDO_MySQL 扩展来替换之。参见 MySQL:选择 API 指南以及相关 FAQ 以获取更多信息。用以替代本函数的有:

mysqli_fetch_assoc() PDOStatement::fetch(PDO::FETCH_ASSOC)

说明

array mysql_fetch_assoc ( resource $result )

返回对应结果集的关联数组,并且继续移动内部数据指针。 mysql_fetch_assoc() 和用 mysql_fetch_array() 加上第二个可选参数 MYSQL_ASSOC 完全相同。它仅仅返回关联数组。

参数

result

resource 型的结果集。此结果集来自对 mysql_query() 的调用。

返回值

返回根据从结果集取得的行生成的关联数组;如果没有更多行则返回 FALSE

如果结果中的两个或以上的列具有相同字段名,最后一列将优先。要访问同名的其它列,要么用 mysql_fetch_row() 来取得数字索引或给该列起个别名。 参见 mysql_fetch_array() 例子中有关别名说明。

范例

Example #1 扩展的 mysql_fetch_assoc() 例子

<?php

$conn = mysql_connect("localhost", "mysql_user", "mysql_password");

if (!$conn) {
    echo "Unable to connect to DB: " . mysql_error();
    exit;
}
  
if (!mysql_select_db("mydbname")) {
    echo "Unable to select mydbname: " . mysql_error();
    exit;
}

$sql = "SELECT id as userid, fullname, userstatus 
        FROM   sometable
        WHERE  userstatus = 1";

$result = mysql_query($sql);

if (!$result) {
    echo "Could not successfully run query ($sql) from DB: " . mysql_error();
    exit;
}

if (mysql_num_rows($result) == 0) {
    echo "No rows found, nothing to print so am exiting";
    exit;
}

// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
// Note: If you put extract($row); inside the following loop, you'll
//       then create $userid, $fullname, and $userstatus
while ($row = mysql_fetch_assoc($result)) {
    echo $row["userid"];
    echo $row["fullname"];
    echo $row["userstatus"];
}

mysql_free_result($result);

?>

注释

Note: 性能

必须指出一个要点: mysql_fetch_assoc() 比 mysql_fetch_row() 并不明显 慢,而且还提供了更多有用的值。

Note: 此函数返回的字段名大小写敏感。

Note: 此函数将 NULL 字段设置为 PHP NULL 值。

参见

mysql_fetch_row() - 从结果集中取得一行作为枚举数组 mysql_fetch_array() - 从结果集中取得一行作为关联数组,或数字数组,或二者兼有 mysql_data_seek() - 移动内部结果的指针 mysql_query() - 发送一条 MySQL 查询 mysql_error() - 返回上一个 MySQL 操作产生的文本错误信息


!!!站长长期在线接!!!

网站、小程序:定制开发/二次开发/仿制开发等

各种疑难杂症解决/定制接口/定制采集等

站长微信:lxwl520520

站长QQ:1737366103