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
- How can the code snippet provided be optimized for better performance and maintainability in PHP?
- How can one ensure that the PHP script for automatic data insertion runs smoothly without manual intervention?
- Are there any best practices for securely managing user credentials in PHP scripts for database connections?