How can SQL injection be prevented in the code?
SQL injection can be prevented by using parameterized queries or prepared statements in your code. This helps to separate SQL code from user input and prevents malicious SQL queries from being executed.
// Using parameterized queries to prevent SQL injection
$pdo = new PDO('mysql:host=localhost;dbname=my_database', 'username', 'password');
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username AND password = :password');
$stmt->execute(['username' => $username, 'password' => $password]);
$user = $stmt->fetch();
Related Questions
- How can HTML5 geolocation APIs be integrated into PHP applications for enhanced functionality?
- What is the correct syntax for comparison in PHP, and why is it important in conditional statements?
- What are some common pitfalls that beginners encounter when working with PHP and databases in a forum setting?