In PHP, when we use to perform database operations, we usually use mysqli_query() to execute the query and use the mysqli_result object to get the result. If you want to convert the query results directly into objects, you can use the mysqli_result::fetch_object() method.
This article will take you step by step into how to use it and demonstrate it with a simple example.
fetch_object() is a method of the mysqli_result class, used to get the current row from the query result and return it as an object. By default, it returns a standard object ( stdClass ) whose property name corresponds to the database field name.
You can also pass in a class name, let the method return an instance of the specified class, and assign the field value to the object attribute.
object mysqli_result::fetch_object ([ string $class_name = "stdClass" [, array $params ]] )
$class_name : The class name to be instantiated, the default is stdClass .
$params : If the class name is specified, the constructor parameter can be passed.
Suppose you have a table called users , the structure is as follows:
id | name | |
---|---|---|
1 | Alice | alice@m66.net |
2 | Bob | bob@m66.net |
Here is the sample code:
<?php
// Connect to the database
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check the connection
if ($mysqli->connect_errno) {
echo "Connection failed: " . $mysqli->connect_error;
exit();
}
// Execute a query
$sql = "SELECT id, name, email FROM users";
$result = $mysqli->query($sql);
if ($result) {
while ($user = $result->fetch_object()) {
echo "ID: " . $user->id . "<br>";
echo "Name: " . $user->name . "<br>";
echo "Email: " . $user->email . "<br><br>";
}
$result->free();
} else {
echo "Query failed: " . $mysqli->error;
}
// Close the connection
$mysqli->close();
?>
In this example, each loop $user is a stdClass object containing the id , name , and email attributes of the current row.
You can also let fetch_object() return a specific class object, such as:
<?php
class User {
public $id;
public $name;
public $email;
public function display() {
echo "[$this->id] $this->name <$this->email><br>";
}
}
$sql = "SELECT id, name, email FROM users";
$result = $mysqli->query($sql);
if ($result) {
while ($user = $result->fetch_object('User')) {
$user->display();
}
$result->free();
}
?>
This way, each time you loop you get a User instance and you can call its methods directly.
If the query result is empty, fetch_object() returns false .
If a class name is specified, the attributes of the class must be public , otherwise the value cannot be assigned directly.
fetch_object() only extracts one row of data at a time and needs to be used in a loop.