What best practices should be followed when passing a PDO object to a class method for database operations in PHP?
When passing a PDO object to a class method for database operations in PHP, it is important to ensure that the PDO object is properly instantiated and passed by reference to the method. This helps maintain a single connection to the database throughout the application, improving performance and reducing resource usage. Additionally, using prepared statements with placeholders can help prevent SQL injection attacks and ensure data integrity.
class DatabaseHandler {
private $pdo;
public function __construct(PDO $pdo) {
$this->pdo = $pdo;
}
public function fetchData($query) {
$stmt = $this->pdo->prepare($query);
$stmt->execute();
return $stmt->fetchAll();
}
}
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
$dbHandler = new DatabaseHandler($pdo);
$data = $dbHandler->fetchData("SELECT * FROM my_table");
Keywords
Related Questions
- What are the key components needed for a simplified version of a web directory that can be easily expanded?
- In what ways can PHP developers improve their problem-solving skills and self-sufficiency when facing coding challenges?
- How does the choice between mysql_*, mysqli_*, PDO, ORM, and Query Builder impact the performance of a PHP application, especially in large projects?