How can SQL injection vulnerabilities be prevented when using $_GET variables in SQL queries in PHP?
SQL injection vulnerabilities can be prevented by using prepared statements with parameterized queries when using $_GET variables in SQL queries in PHP. This helps to sanitize the input data and prevent malicious SQL code from being executed.
// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
// Prepare a SQL statement with a placeholder for the parameter
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
// Bind the parameter value to the placeholder
$stmt->bindParam(':id', $_GET['id']);
// Execute the statement
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll();
Related Questions
- How can timestamps be effectively used in PHP to create daily folders for storing invoices or other files?
- What are best practices for securely integrating CGI commands into PHP applications for controlling external devices like NETIO Steckdosen?
- What are the best practices for tabular data representation in HTML, and why should tables not be used for layout purposes?