What are the potential security risks associated with directly passing user input ($_GET['id']) into a database query in PHP, and how can these risks be mitigated?
Passing user input directly into a database query without proper sanitization can lead to SQL injection attacks, where malicious code is injected into the query to manipulate the database. To mitigate this risk, it is essential to sanitize and validate user input before using it in a query.
$id = isset($_GET['id']) ? intval($_GET['id']) : 0; // Sanitize the input by converting it to an integer
$stmt = $pdo->prepare("SELECT * FROM table WHERE id = :id");
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
Related Questions
- What best practices should be followed when updating multiple records in a database using PHP scripts, especially in terms of error handling and data validation?
- What are the best practices for handling file permissions when using fopen in PHP?
- Are there any potential pitfalls to using unset in PHP when working with arrays?