Page 1 of 1

How do I code my Previous/Next Button to show next item

Posted: Thu Jan 10, 2013 3:45 am
by adsegzy
Hello Friends,

I need your help. I have a website where articles are submitted. On the read_article.php page, i retrieve my data from the mysql DB like this.

Code: Select all

<?php
$id = $_GET[id];

$get = mysql_query('SELECT * FROM articles WHERE id='$id'');
$rows = mysql_fetch_array($get);{
$id = $rows[id];
$topic = $rows[topic];
$body = $rows[body];
}
?>
I did my Previous and next button like this
<a href='read_article.php?id=<?php echo $id--; ?>'>Previous Article</a>
<a href='read_article.php?id=<?php echo $id++; ?>'>Next Article</a>

if the current Article $id is 5, Clicking on Next Articles will show Articles whose $id is 6. But in case articles with $id 6,7 & 8 have been deleted, meaning the next available article is 9.
How do I make my next button go straight from $id 5 to $id 9

Thanks

Re: How do I code my Previous/Next Button to show next item

Posted: Thu Jan 10, 2013 7:39 pm
by requinix
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

Re: How do I code my Previous/Next Button to show next item

Posted: Tue Jan 29, 2013 8:30 am
by adsegzy
Thank You requinix,

I didnt even think towards this direction. It's now working as i pleased.

Well done