How can SQL injections be prevented when embedding PHP variables in SQL queries?
To prevent SQL injections when embedding PHP variables in SQL queries, you can use prepared statements with parameterized queries. This method separates the SQL query logic from the user input, making it impossible for malicious users to inject SQL code into the query.
// Using prepared statements with parameterized queries to prevent SQL injections
$pdo = new PDO("mysql:host=localhost;dbname=myDB", "username", "password");
// Prepare a SQL query with a placeholder for the user input
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
// Bind the user input to the placeholder
$stmt->bindParam(':username', $username);
// Execute the query
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll();