How can the PHP code be optimized to prevent SQL injection vulnerabilities?
To prevent SQL injection vulnerabilities in PHP code, it is important to use prepared statements with parameterized queries when interacting with a database. This approach separates SQL logic from user input, preventing malicious SQL queries from being executed.
// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
// Prepare a SQL statement with placeholders
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
// Bind parameters to placeholders
$stmt->bindParam(':username', $_POST['username']);
// Execute the statement
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);