What are the potential security risks when connecting to a database in PHP?
One potential security risk when connecting to a database in PHP is SQL injection attacks, where malicious SQL queries are inserted into input fields. To prevent this, you should always use prepared statements with parameterized queries to sanitize user input.
// Establish a connection to the database using PDO
$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) {
die('Connection failed: ' . $e->getMessage());
}