What is the purpose of using PDO::FETCH_CLASS in PHP?
When fetching data from a database using PDO in PHP, the default fetch mode is to return an array. However, using PDO::FETCH_CLASS allows you to fetch the data directly into an object of a specified class, making it easier to work with the data in an object-oriented manner.
class User {
public $id;
public $username;
public $email;
}
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
$stmt->execute(['id' => 1]);
$user = $stmt->fetch(PDO::FETCH_CLASS, 'User');
echo $user->username;
Related Questions
- What are the advantages and disadvantages of using prefixes in variable names in PHP, and how does it affect code readability and maintenance?
- Are there any specific guidelines or best practices to follow when implementing a FULLTEXT search feature in PHP using MySQL databases?
- How can PHPTAL be integrated with XML parsers for more efficient code processing in PHP applications?