What are common pitfalls when using $_GET to retrieve data from a database in PHP?
One common pitfall when using $_GET to retrieve data from a database in PHP is not properly sanitizing the input, which can lead to SQL injection attacks. To prevent this, you should always sanitize and validate the input before using it in a database query. Another pitfall is not checking if the required parameters are set in the $_GET array before using them, which can result in errors or unexpected behavior.
// Sanitize and validate the input from $_GET before using it in a database query
$id = isset($_GET['id']) ? filter_var($_GET['id'], FILTER_SANITIZE_NUMBER_INT) : null;
if($id) {
// Use the sanitized input in a database query
$stmt = $pdo->prepare("SELECT * FROM table WHERE id = :id");
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetch();
// Process the result
if($result) {
// Do something with the data
} else {
// Handle the case where no data is found
}
} else {
// Handle the case where the required parameter is not set
}