How can object-oriented programming principles be applied to improve the handling of SQL query results in PHP?

When handling SQL query results in PHP, object-oriented programming principles can be applied to create classes that represent the data being fetched from the database. This allows for better organization, encapsulation, and reusability of code when working with query results.

// Define a class to represent a row of data from the SQL query result
class UserData {
    public $id;
    public $name;
    public $email;

    public function __construct($id, $name, $email) {
        $this->id = $id;
        $this->name = $name;
        $this->email = $email;
    }
}

// Fetch data from SQL query and create objects of the defined class
$query = "SELECT id, name, email FROM users";
$result = $mysqli->query($query);

$userData = [];
while ($row = $result->fetch_assoc()) {
    $userData[] = new UserData($row['id'], $row['name'], $row['email']);
}

// Now $userData array contains objects representing each row of data fetched from the query