How can SQL injection vulnerabilities be prevented when passing user input to a SQL query in PHP?
SQL injection vulnerabilities can be prevented by using prepared statements with parameterized queries in PHP. This method ensures that user input is treated as data rather than executable code, thus protecting against malicious SQL injection attacks.
// Using prepared statements to prevent SQL injection
$pdo = new PDO('mysql:host=localhost;dbname=myDB', 'username', 'password');
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
$stmt->bindParam(':username', $_POST['username']);
$stmt->execute();
$results = $stmt->fetchAll();
Related Questions
- What are some best practices for handling user login and displaying user data in PHP projects?
- In what scenarios should PHP developers consider transitioning from procedural code to object-oriented code for better code maintenance?
- What are the common pitfalls in integrating PHP scripts into HTML documents, and how can they be avoided?