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.
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.
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);
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";
}
<?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();
?>