How can the PHP code be improved to prevent SQL injection attacks?
To prevent SQL injection attacks in PHP, you should use prepared statements with parameterized queries instead of directly inserting user input into SQL queries. This helps to separate SQL logic from user input, preventing malicious SQL code from being executed.
// Improved PHP code to prevent SQL injection attacks using prepared statements
// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// User input
$userInput = $_POST['user_input'];
// Prepare a SQL statement with a placeholder
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
// Bind the user input to the prepared statement
$stmt->bindParam(':username', $userInput);
// Execute the prepared statement
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll();
// Process the results as needed
foreach ($results as $row) {
// Output or manipulate the data
}