How can PDO be used to retrieve an array of objects in PHP, and what are the potential pitfalls?

To retrieve an array of objects using PDO in PHP, you can use the fetchAll method after executing a query with PDO. This method fetches all rows from the result set as an array of objects. One potential pitfall to be aware of is the memory usage when fetching a large number of rows as objects can consume more memory compared to fetching as arrays.

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

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

// Fetch all rows as an array of objects
$results = $stmt->fetchAll(PDO::FETCH_OBJ);

// Loop through the array of objects
foreach ($results as $result) {
    // Do something with each object
    echo $result->column_name . "<br>";
}