What security considerations should be taken into account when connecting to a MySQL database using PHP?
When connecting to a MySQL database using PHP, it is important to avoid SQL injection attacks by using prepared statements and parameterized queries. Additionally, it is crucial to securely store database credentials and not expose them in the code. Finally, limiting the privileges of the database user used by the PHP application to only necessary permissions can help mitigate security risks.
<?php
// Securely store database credentials in a separate file
include 'config.php';
// Create a PDO connection with prepared statements
try {
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
die("Error: " . $e->getMessage());
}