How can PHP scripts be modified to prevent SQL injection attacks when retrieving data from a database?
To prevent SQL injection attacks when retrieving data from a database in PHP scripts, developers should use prepared statements with parameterized queries. This approach separates SQL logic from user input, making it impossible for malicious input to alter the SQL query structure. By binding parameters to the 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=mydatabase", "username", "password");
// Prepare a SQL statement with a parameterized query
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
// Bind the parameter and execute the query
$stmt->bindParam(':username', $_POST['username']);
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Loop through the results and display them
foreach ($results as $row) {
echo $row['username'] . "<br>";
}
Related Questions
- How can checking the HTTP header Content-Type and meta charset tags help resolve Umlaut display issues in PHP?
- What are some best practices for separating PHP logic from CSS styling in web development?
- What are the potential challenges of using PHP-Documentor on a standard web space without using the console?