PHP Data Objects (PDO) is a database access layer that provides a uniform method of interaction with multiple database systems such as MySQL, SQLite, and PostgreSQL. It improves security and flexibility when working with databases.
A PDO connection is created using a Data Source Name (DSN), username, and password. Error handling is commonly managed using exceptions for better debugging and control.
// Create a PDO connection to a MySQL database
setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully using PDO!";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
If the connection is successful, the message Connected successfully using PDO! will be displayed. If an error occurs, the exception message will describe the issue.
This PDO connection example can be expanded by adding prepared statements and fetching data dynamically, making it suitable for real-world database-driven applications.