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
- How can SQL Injection be prevented when using Prepared statements with IN clause in MySQLi?
- How can developers effectively handle authentication and authorization when using Bitbucket API in PHP applications?
- How can including the main.php file instead of using the header function improve the user experience and overall functionality of the login script?