目录

PHP mysqli fetch_object() 函数

❮ PHP MySQLi 参考

示例 - 面向对象风格

返回结果集的当前行,然后打印每个字段的值:

<?php
$mysqli = new mysqli("localhost","my_user","my_password","my_db");

if ($mysqli -> connect_errno) {
  echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
  exit();
}

$sql = "SELECT Lastname, Age FROM Persons ORDER BY Lastname";

if ($result = $mysqli -> query($sql)) {
  while ($obj = $result -> fetch_object()) {
    printf("%s (%s)\n", $obj->Lastname, $obj->Age);
  }
  $result -> free_result();
}

$mysqli -> close();
?>

查看底部的程序样式示例。


定义和用法

fetch_object() / mysqli_fetch_object() 函数将结果集的当前行作为对象返回。

笔记:从此函数返回的字段名称区分大小写。


语法

面向对象风格:

$mysqli_result -> fetch_object( classname, params)

程序风格:

mysqli_fetch_object( result, classname, params)

参数值

Parameter Description
result Required. Specifies a result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result()
classname Optional. Specifies the name of the class to instantiate, set the properties of, and return
params Optional. Specifies an array of parameters to pass to the constructor for classname objects

技术细节

返回值: 返回具有所获取行的字符串属性的对象。如果结果集中没有更多行,则为 NULL
PHP 版本: 5+
变更日志: PHP 5.0.0 中添加了作为不同对象返回的功能

示例 - 程序风格

返回结果集的当前行,然后打印每个字段的值:

<?php
$con = mysqli_connect("localhost","my_user","my_password","my_db");

if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  exit();  
}

$sql = "SELECT Lastname, Age FROM Persons ORDER BY Lastname";

if ($result = mysqli_query($con, $sql)) {
  while ($obj = mysqli_fetch_object($result)) {
    printf("%s (%s)\n", $obj->Lastname, $obj->Age);
  }
  mysqli_free_result($result);
}

mysqli_close($con);
?>


❮ PHP MySQLi 参考