Can you provide an example of how to properly define and use a PDO connection in a PHP class?
When working with databases in PHP, it is recommended to use PDO (PHP Data Objects) for secure and efficient database connections. To define and use a PDO connection in a PHP class, you can create a constructor method that initializes the connection using the appropriate database credentials. This allows you to easily reuse the connection throughout your class methods.
class Database {
private $host = 'localhost';
private $db_name = 'your_database_name';
private $username = 'your_username';
private $password = 'your_password';
private $conn;
public function __construct() {
$dsn = "mysql:host={$this->host};dbname={$this->db_name}";
try {
$this->conn = new PDO($dsn, $this->username, $this->password);
} catch (PDOException $e) {
die("Connection failed: " . $e->getMessage());
}
}
// Other class methods can now use $this->conn for database operations
}