How can a PDO connection be defined in a class and used further in PHP?
To define a PDO connection in a class in PHP, you can create a constructor method in the class that establishes the connection using the PDO class. You can then store the PDO object as a property of the class for further use in other methods.
class Database {
private $pdo;
public function __construct($host, $dbname, $username, $password) {
$dsn = "mysql:host=$host;dbname=$dbname";
$this->pdo = new PDO($dsn, $username, $password);
}
public function query($sql) {
return $this->pdo->query($sql);
}
}
// Usage
$db = new Database('localhost', 'mydatabase', 'username', 'password');
$result = $db->query('SELECT * FROM users');
Keywords
Related Questions
- Are there any potential pitfalls to be aware of when using the explode function in PHP to separate strings?
- How can the code be modified to incorporate CSS classes for styling the elements instead of inline styling?
- How can the use of $_POST and $_GET variables improve the security and efficiency of PHP scripts?