How can SQL injection be prevented in PHP when handling user input from forms?
SQL injection can be prevented in PHP when handling user input from forms by using prepared statements with parameterized queries. This method separates the SQL query from the user input, preventing malicious SQL code from being executed. By using prepared statements, the input is treated as data rather than executable code, making it secure against SQL injection attacks.
// Establish a connection to the database
$pdo = new PDO('mysql:host=localhost;dbname=your_database', 'username', 'password');
// Prepare a SQL statement 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']);
// Execute the query
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll();