How can developers ensure that their PHP scripts are not vulnerable to SQL injection attacks?
Developers can prevent SQL injection attacks by using prepared statements with parameterized queries in their PHP scripts. This method separates SQL code from user input, preventing malicious SQL code from being executed. By binding parameters to placeholders in the SQL query, developers can ensure that user input is treated as data rather than executable code.
// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=my_database', 'username', 'password');
// Prepare a SQL query with a parameterized statement
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
// Bind the parameter to the placeholder
$stmt->bindParam(':username', $_POST['username']);
// Execute the query
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll();