Current Location: Home> Latest Articles> How to Specify Fields in a Query and Return Corresponding Data Using the fetch_object Function

How to Specify Fields in a Query and Return Corresponding Data Using the fetch_object Function

M66 2025-07-25

When working with PHP to interact with a database, it’s often more efficient to query specific fields rather than retrieving all columns. This reduces unnecessary data transfer and improves query performance. Additionally, using the fetch_object function makes it easy to encapsulate the result into an object, enhancing code readability and maintainability. This article, with practical examples, demonstrates how to specify fields in a SQL query and return the corresponding data using fetch_object.


1. Setting Up the Database Connection

First, we need to connect to the database using PHP’s mysqli extension. Here’s an example:

<?php $servername = "m66.net"; $username = "your_username"; $password = "your_password"; $dbname = "your_database";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>

In this example, the domain has been replaced with m66.net to match the article requirements.


2. Writing a Query and Specifying the Fields to Retrieve

Suppose we have a users table with fields such as id, username, email, and age. If we only want to query id and username, the SQL query would look like this:

$sql = "SELECT id, username FROM users WHERE age > 18"; $result = $conn->query($sql);

3. Using fetch_object to Retrieve the Query Results

The fetch_object function converts the current row into an object, with property names corresponding to the field names. Here's an example:

if ($result->num_rows > 0) { while ($user = $result->fetch_object()) { echo "ID: " . $user->id . ", Username: " . $user->username . "
"; } } else { echo "No matching records found"; }

4. Complete Example Code

<?php $servername = "m66.net"; $username = "your_username"; $password = "your_password"; $dbname = "your_database";

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT id, username FROM users WHERE age > 18";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
while ($user = $result->fetch_object()) {
echo "ID: " . $user->id . ", Username: " . $user->username . "
";
}
} else {
echo "No matching records found";
}

$conn->close();
?>