Function name: mysqli_result::fetch_object() Applicable version: PHP 5, PHP 7
Function Description: This function is used to obtain the next row from the result set as an object and return the object. The attribute name of the object corresponds to the column name of the result set.
Syntax: mixed mysqli_result::fetch_object ( string $class_name = "stdClass" , array $params = array )
parameter:
Return value: Return an object when successful, and return NULL when failure.
Example:
// 假设已经建立了数据库连接$conn,并执行了查询语句$query // 使用默认的类名"stdClass",返回一个标准对象$result = $conn->query($query); if ($result->num_rows > 0) { while ($row = $result->fetch_object()) { echo $row->name . ", " . $row->age . "<br>"; } } // 自定义类名和构造函数参数class Person { public $name; public $age; public function __construct($name, $age) { $this->name = $name; $this->age = $age; } } $result = $conn->query($query); if ($result->num_rows > 0) { while ($row = $result->fetch_object("Person", ["John", 30])) { echo $row->name . ", " . $row->age . "<br>"; } }
In the above example, first we execute a query statement and get the result set $result. We then loop through each row in the result set using while loop. In each loop, we use the fetch_object() method to convert the current row into an object. If we use the default class name "stdClass", we can directly access the column's value through the object's property name. If we specify a custom class name and constructor parameters, we need to define the corresponding attribute in the class and receive the parameters in the constructor and assign them to the attribute.