How can SQL injections be prevented in PHP when input is stored in a database and later displayed on a webpage?
SQL injections can be prevented in PHP by using prepared statements with parameterized queries. This approach separates the SQL query from the user input, preventing malicious code from being executed. By binding parameters to placeholders in the query, the database engine can distinguish between the query structure and the user input.
// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
// Prepare a SQL query with a placeholder for user input
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
// Bind the user input to the placeholder
$stmt->bindParam(':username', $_POST['username'], PDO::PARAM_STR);
// Execute the query
$stmt->execute();
// Fetch and display the results
while ($row = $stmt->fetch()) {
echo $row['username'] . "<br>";
}