How can PHP developers handle SQL injection vulnerabilities in their code?
SQL injection vulnerabilities can be handled by using prepared statements with parameterized queries in PHP. This involves separating SQL code from user input, which helps prevent malicious SQL code from being injected into the query. By using prepared statements, developers can ensure that user input is treated as data rather than executable code.
// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Prepare a SQL query using 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();