To fetch records into a custom PHP class using PDO in PHP, you can follow these steps:
User
class:class User {
public $id;
public $name;
public $email;
}
$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();
}
$query = "SELECT id, name, email FROM users";
$stmt = $db->prepare($query);
$stmt->execute();
$users = $stmt->fetchAll(PDO::FETCH_CLASS, 'User');
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.