How can prepared statements in mysqli or PDO be utilized to prevent SQL injection attacks in PHP applications?
SQL injection attacks can be prevented in PHP applications by using prepared statements in mysqli or PDO. Prepared statements separate the SQL query from the user input, preventing malicious SQL code from being injected into the query. This ensures that user input is treated as data rather than executable code.
// Using prepared statements with PDO to prevent SQL injection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username AND password = :password");
$stmt->bindParam(':username', $username);
$stmt->bindParam(':password', $password);
$stmt->execute();
// Using prepared statements with mysqli to prevent SQL injection
$mysqli = new mysqli("localhost", "username", "password", "mydatabase");
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ? AND password = ?");
$stmt->bind_param("ss", $username, $password);
$stmt->execute();