How can SQL injection be prevented when using GET data in a query?
SQL injection can be prevented when using GET data in a query by using prepared statements with parameterized queries. This approach ensures that user input is treated as data rather than executable code, effectively preventing malicious SQL injection attacks.
// 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 GET parameter to the query
$stmt->bindParam(':username', $_GET['username']);
// Execute the query
$stmt->execute();
// Fetch results
$results = $stmt->fetchAll();
Related Questions
- How can beginners in PHP effectively manage and troubleshoot formatting issues with multi-line text input and output fields in a database?
- How can the issue of passing null values to string functions like strpos() and str_replace() be mitigated in PHP 8.1 to avoid deprecated warnings and errors?
- How can debugging be improved in PHP scripts that handle JSON data, especially in AJAX requests?