How can a PHP beginner effectively utilize SQL queries to retrieve the next and previous news articles based on the current news being viewed?
To retrieve the next and previous news articles based on the current news being viewed, a PHP beginner can use SQL queries with conditions to fetch the appropriate data. By ordering the news articles by date or ID, the next and previous articles can be determined. The PHP script can then display the retrieved articles accordingly.
// Assuming $currentNewsId contains the ID of the current news article being viewed
// Retrieve the next news article
$sqlNext = "SELECT * FROM news WHERE id > $currentNewsId ORDER BY id ASC LIMIT 1";
$resultNext = mysqli_query($connection, $sqlNext);
$nextNews = mysqli_fetch_assoc($resultNext);
// Retrieve the previous news article
$sqlPrev = "SELECT * FROM news WHERE id < $currentNewsId ORDER BY id DESC LIMIT 1";
$resultPrev = mysqli_query($connection, $sqlPrev);
$prevNews = mysqli_fetch_assoc($resultPrev);
// Display the next and previous news articles
if ($prevNews) {
echo "Previous News: " . $prevNews['title'];
}
if ($nextNews) {
echo "Next News: " . $nextNews['title'];
}