How can OOP principles be applied effectively in PHP when using PDO for database interactions?
To apply OOP principles effectively in PHP when using PDO for database interactions, you can create a separate class for database connection and interaction, encapsulating the database logic within methods of this class. This helps in separating concerns and promoting code reusability and maintainability.
class Database {
private $host = 'localhost';
private $dbname = 'my_database';
private $username = 'root';
private $password = '';
private $connection;
public function __construct() {
$this->connection = new PDO("mysql:host=$this->host;dbname=$this->dbname", $this->username, $this->password);
$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
public function executeQuery($query, $params = []) {
$statement = $this->connection->prepare($query);
$statement->execute($params);
return $statement->fetchAll(PDO::FETCH_ASSOC);
}
public function insertData($table, $data) {
$keys = implode(',', array_keys($data));
$values = implode(',', array_fill(0, count($data), '?'));
$query = "INSERT INTO $table ($keys) VALUES ($values)";
$this->executeQuery($query, array_values($data));
}
}
// Example usage
$db = new Database();
$db->insertData('users', ['name' => 'John Doe', 'email' => 'john@example.com']);