How can PHP developers prevent SQL injection attacks when interacting with a database?
SQL injection attacks can be prevented by using prepared statements and parameterized queries when interacting with a database in PHP. This helps to separate SQL code from user input, making it impossible for malicious input to alter the SQL query structure.
// Establish a connection to the database
$pdo = new PDO('mysql:host=localhost;dbname=my_database', 'username', 'password');
// Prepare a SQL statement with a placeholder for user input
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
// Bind the user input to the placeholder
$stmt->bindParam(':username', $_POST['username']);
// Execute the query
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll();