What are best practices for handling SQL injection in PHP code?
SQL injection can be prevented in PHP code by using prepared statements and parameterized queries instead of directly inserting user input into SQL queries. This helps to sanitize user input and prevent malicious SQL queries from being executed. Example PHP code snippet using prepared statements to prevent SQL injection:
// Establish a connection to the database
$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 the placeholders
$stmt->bindParam(':username', $_POST['username']);
// Execute the prepared statement
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll();
// Loop through the results and do something with them
foreach ($results as $row) {
// Do something with the data
}