What are the advantages of using PDO for database connections in PHP projects?
When working with databases in PHP projects, it is important to use a secure and reliable method for connecting to the database. PDO (PHP Data Objects) provides a flexible and secure way to interact with databases, offering support for multiple database types and prepared statements to prevent SQL injection attacks. By using PDO, developers can write cleaner and more maintainable code that is less prone to security vulnerabilities.
// Connect to a MySQL database using PDO
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}