What are best practices for handling article IDs and titles in URLs when retrieving data from a MySQL database in PHP?
When retrieving data from a MySQL database in PHP, it is important to handle article IDs and titles in URLs properly to ensure security and SEO optimization. One common practice is to use the article ID in the URL for database queries, while using the article title for SEO-friendly URLs. To achieve this, you can encode the article title using functions like urlencode() and decode it before querying the database.
// Assuming $articleId is the ID retrieved from the URL and $articleTitle is the title
$articleId = $_GET['id'];
$articleTitle = $_GET['title'];
// Decode the article title for querying the database
$decodedTitle = urldecode($articleTitle);
// Query the database using the article ID
$query = "SELECT * FROM articles WHERE id = $articleId AND title = '$decodedTitle'";
$result = mysqli_query($connection, $query);
// Fetch data and display
if(mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
echo "Article Title: " . $row['title'];
echo "Article Content: " . $row['content'];
} else {
echo "Article not found";
}