How can PDO and prepared statements be used in PHP to enhance security and prevent SQL Injection when working with databases?
SQL Injection is a common security vulnerability where an attacker can manipulate SQL queries through input forms to access or modify data in a database. To prevent SQL Injection, developers can use PDO (PHP Data Objects) along with prepared statements in PHP. PDO provides a secure way to connect to databases, and prepared statements allow developers to separate SQL logic from user input, reducing the risk of SQL Injection attacks.
// 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);
} catch (PDOException $e) {
die('Connection failed: ' . $e->getMessage());
}
// Use prepared statements to safely execute SQL queries
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
$stmt->bindParam(':username', $_POST['username']);
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);