What are the best practices for handling user input in SQL queries to prevent SQL injection vulnerabilities?
SQL injection vulnerabilities can occur when user input is directly incorporated into SQL queries without proper sanitization. To prevent this, it is recommended to use parameterized queries or prepared statements, which separate the SQL query from the user input, thus preventing malicious SQL code from being executed.
// Using parameterized queries to prevent SQL injection
// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// User input
$user_input = $_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 placeholder
$stmt->bindParam(':username', $user_input);
// Execute the query
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Use the results as needed
foreach ($results as $row) {
echo $row['username'] . "<br>";
}