Do a query - two actually - to find the previous and next articles' IDs. Be sure to define "previous" and "next" as something that makes sense: an ID number is arbitrary and, say, a date probably makes more sense.
Also, SQL injection. Never put $_POST or $_GET values directly into a query.
Also, the mysql extension and mysql_* functions are old and shouldn't be used anywhere. Try mysqli or PDO instead. And you seem to be missing a mysql_connect().
Also, what if I go to read_article.php without giving an ID?
Also, strings always need quotes, even if they're array keys.
Also, the {}s in your code mean nothing and are misleading (I see a } and think there's a loop somewhere).
Code: Select all
<?php
if (!isset($_GET["id"])) {
// didn't give an ID
// show an error or show the most recent article or redirect somewhere or whatever
}
$pdo = new PDO("mysql:host=hostname;dbname=database name", "username", "password");
$stmt = $pdo->prepare("SELECT * FROM articles WHERE id = :id");
$stmt->execute(array(":id" => $_GET["id"]));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$id = $row["id"];
$published = $row["published"];
$topic = $row["topic"];
$body = $row["body"];
Code: Select all
$stmt = $pdo->prepare("SELECT id FROM articles WHERE published < :published ORDER BY published DESC LIMIT 1");
$stmt->execute(array(":published" => $row["published"]));
$previous = $stmt->fetch(PDO::FETCH_ASSOC);
// $previous will be empty if $row is the first one
$stmt = $pdo->prepare("SELECT id FROM articles WHERE published > :published ORDER BY published ASC LIMIT 1");
$stmt->execute(array(":published" => $row["published"]));
$next = $stmt->fetch(PDO::FETCH_ASSOC);
// $next will be empty if $row is the last one