How does using PDO in PHP contribute to object-oriented programming principles?
Using PDO in PHP contributes to object-oriented programming principles by encapsulating database access logic within objects. This allows for better organization and separation of concerns in the codebase. Additionally, PDO provides a consistent and secure way to interact with databases, promoting reusability and maintainability of code.
// Establish a PDO connection to a MySQL database
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'username';
$password = 'password';
try {
$pdo = new PDO($dsn, $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
Related Questions
- Are there any potential pitfalls or security risks associated with storing database "ID" as a session variable in PHP?
- What are best practices for preventing session hijacking in PHP applications?
- What steps can be taken to troubleshoot and resolve issues with PHPUnit not functioning as expected in a Laravel project?