How to fetch records into a custom PHP class using PDO in PHP?

To fetch records into a custom PHP class using PDO in PHP, you can follow these steps:

  1. Create a custom PHP class to represent the data you want to fetch. For example, let's say you have a User class:
class User { public $id; public $name; public $email; }
  1. Connect to the database using PDO:
$dsn = "mysql:host=localhost;dbname=mydatabase"; $username = "username"; $password = "password"; try { $db = new PDO($dsn, $username, $password); } catch (PDOException $e) { echo "Connection failed: " . $e->getMessage(); }
  1. Prepare and execute a SELECT query:
$query = "SELECT id, name, email FROM users"; $stmt = $db->prepare($query); $stmt->execute();
  1. Fetch the records and store them in instances of the custom class:
$users = $stmt->fetchAll(PDO::FETCH_CLASS, 'User');
  1. Now you can work with the retrieved records as instances of the User class:
foreach ($users as $user) { echo $user->id . ", " . $user->name . ", " . $user->email . "<br>"; }

This will fetch the records from the database and store them in an array of User objects, allowing you to easily access the data using object properties.