What are the best practices for sanitizing user input before executing SQL queries in PHP?
When executing SQL queries in PHP, it is crucial to sanitize user input to prevent SQL injection attacks. One of the best practices for sanitizing user input is to use prepared statements with parameterized queries. This method separates the SQL query logic from the user input, making it impossible for malicious input to alter the structure of the query.
// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
// Sanitize user input using prepared statements
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $_POST['username']);
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Loop through the results
foreach ($results as $row) {
echo $row['username'] . "<br>";
}