How can data be retrieved from a database in PHP using objects instead of arrays, and what are the benefits of this approach?

To retrieve data from a database in PHP using objects instead of arrays, you can use the PDO class which allows you to fetch data as objects. This approach can provide more structured and organized data retrieval, making it easier to work with object-oriented programming principles. Additionally, using objects can offer better encapsulation and abstraction of data, leading to cleaner and more maintainable code.

// Connect to the database
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

// Prepare and execute a query
$stmt = $pdo->query("SELECT * FROM mytable");

// Fetch data as objects
while ($row = $stmt->fetch(PDO::FETCH_OBJ)) {
    // Access data using object properties
    echo $row->column1 . " " . $row->column2 . "<br>";
}