PHP  
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | my php.net 
search for in the  
<mysql_fetch_arraymysql_fetch_field>
Last updated: Mon, 16 Jul 2012

mysql_fetch_assoc

(PHP 4 >= 4.0.3, PHP 5)

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

说明

array mysql_fetch_assoc ( resource result )

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

mysql_fetch_assoc() 和用 mysql_fetch_array() 加上第二个可选参数 MYSQL_ASSOC 完全相同。它仅仅返回关联数组。这也是 mysql_fetch_array() 起初始的工作方式。如果在关联索引之外还需要数字索引,用 mysql_fetch_array()

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

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

注: 本函数返回的字段名是区分大小写的。

例子 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);

?>

参见 mysql_fetch_row()mysql_fetch_array()mysql_query()mysql_error()




<mysql_fetch_arraymysql_fetch_field>
 Last updated: Mon, 16 Jul 2012
 
Copyright © 2001-2005 The PHP Group
All rights reserved.
This unofficial mirror is operated at: http://manual.phpv.net/
Last updated: Thu Jul 7 19:13:47 2005 CST