How can one improve the code provided to make the link index.php?page=news&id=1 functional?
The issue with the provided code is that the link index.php?page=news&id=1 is not functional because the $_GET['page'] and $_GET['id'] variables are not being properly handled in the PHP code. To make the link functional, we need to check if these variables are set and then use them to determine which page to display and which news article to show based on the id.
<?php
// Check if the page and id parameters are set
if(isset($_GET['page']) && isset($_GET['id'])) {
// Sanitize the input to prevent SQL injection
$page = $_GET['page'];
$id = $_GET['id'];
// Display the news article with the specified id
if($page === 'news') {
// Query the database for the news article with the specified id
// Display the news article content
echo "Displaying news article with id $id";
} else {
// Display a 404 error page if the page is not found
header("HTTP/1.0 404 Not Found");
echo "404 Page Not Found";
}
} else {
// Display a default page if the parameters are not set
echo "Welcome to the homepage!";
}
?>
Related Questions
- What are common pitfalls when using PHP to validate form submissions?
- What resources or documentation can be helpful for understanding and implementing date-related functions in PHP?
- What are the best practices for handling UTF-8 encoding and character set configurations in PHP databases to avoid data corruption?