How can prepared statements and PDO (or mysqli_) be utilized to enhance the security of database queries in PHP?
Using prepared statements with PDO or mysqli_ in PHP can enhance the security of database queries by automatically escaping input parameters and preventing SQL injection attacks. Prepared statements separate SQL logic from data, allowing the database to distinguish between code and data, thereby reducing the risk of malicious SQL injection.
// Using prepared statements with PDO
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
$stmt->bindParam(':username', $username);
$stmt->execute();
$results = $stmt->fetchAll();
// Using prepared statements with mysqli_
$mysqli = new mysqli('localhost', 'username', 'password', 'mydatabase');
$stmt = $mysqli->prepare('SELECT * FROM users WHERE username = ?');
$stmt->bind_param('s', $username);
$stmt->execute();
$results = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);