MySQL 函数
PHP Manual

mysql_fetch_object

(PHP 4, PHP 5)

mysql_fetch_object从结果集中取得一行作为对象

说明

object mysql_fetch_object ( resource $result )

返回根据所取得的行生成的对象,如果没有更多行则返回 FALSE

mysql_fetch_object()mysql_fetch_array() 类似,只有一点区别 - 返回一个对象而不是数组。间接地也意味着只能通过字段名来访问数组,而不是偏移量(数字是合法的属性名)。

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

<?php

/* this is valid */
echo $row->field;
/* this is invalid */
echo $row->0;

?>

速度上,本函数和 mysql_fetch_array() 一样,也几乎和 mysql_fetch_row() 一样快(差别很不明显)。

Example #1 mysql_fetch_object() 例子

<?php
mysql_connect
("hostname""user""password");
mysql_select_db("mydb");
$result mysql_query("select * from mytable");
while (
$row mysql_fetch_object($result)) {
    echo 
$row->user_id;
    echo 
$row->fullname;
}
mysql_free_result($result);
?>

参见 mysql_fetch_array()mysql_fetch_assoc()mysql_fetch_row()

参数

result

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

class_name

The name of the class to instantiate, set the properties of and return. If not specified, a stdClass object is returned.

params

An optional array of parameters to pass to the constructor for class_name objects.

返回值

Returns an object with string properties that correspond to the fetched row, or FALSE if there are no more rows.

更新日志

版本 说明
5.0.0 Added the ability to return as a different object.

范例

Example #2 mysql_fetch_object() example

<?php
mysql_connect
("hostname""user""password");
mysql_select_db("mydb");
$result mysql_query("select * from mytable");
while (
$row mysql_fetch_object($result)) {
    echo 
$row->user_id;
    echo 
$row->fullname;
}
mysql_free_result($result);
?>

Example #3 mysql_fetch_object() example

<?php
class foo {
    public 
$name;
}

mysql_connect("hostname""user""password");
mysql_select_db("mydb");

$result mysql_query("select name from mytable limit 1");
$obj mysql_fetch_object($result'foo');
var_dump($obj);
?>

注释

Note: Performance

Speed-wise, the function is identical to mysql_fetch_array(), and almost as quick as mysql_fetch_row() (the difference is insignificant).

Note:

mysql_fetch_object() is similar to mysql_fetch_array(), with one difference - an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names).

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

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

参见


MySQL 函数
PHP Manual