jlhasson
jlhasson

Reputation: 2286

How to link to a database page

I have a page displaying the titles of articles in my database. They are links and when clicked go to a separate page that I want to display the title and content according to the id. The link looks like this:

        echo '<h2><a href="../../pages/content_page/contents_page.php?id='.$review_id.'">'.$title.'</a></h2>';

and the page displaying them has this code:

<?php
while ($row = mysql_fetch_assoc($query)){
    $review_id = $row['review_id'];
    $title = $row['title'];
    $review = $row['review'];
} ?>
<h1><?php echo $title; ?></h1><br /><br />

<p><?php echo $review; ?></p>

But when I click a link, the url shows the correct id number but the title and content showing is the same for every link that I click. How do I get them to change for each separate id? Thanks in advance!

EDIT:

Full code here:

<?php

include '../../mysql_server/connect_to_mysql.php';

$query = mysql_query("SELECT `review_id`, `title`, `review` FROM `reviews`");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Posts!</title>

<body>

<?php
while ($row = mysql_fetch_assoc($query)){
    $review_id = $row['review_id'];
    $title = $row['title'];
    $review = $row['review'];
} ?>
<h1><?php echo $title; ?></h1><br /><br />

<p><?php echo $review; ?></p>
</body>
</html>

Upvotes: 1

Views: 1174

Answers (2)

Mark Byers
Mark Byers

Reputation: 838076

You are fetching all rows. You need a WHERE clause.

$review_id = intval($_GET['review_id']);
$resource = mysql_query("SELECT title, review FROM reviews
                         WHERE review_id = $review_id");
if (!$resource) {
    trigger_error(mysql_error());
}
# etc..

Upvotes: 1

honyovk
honyovk

Reputation: 2747

Try something like this...

<?php
$id = $_GET['id'];
$query = mysql_query("SELECT `title`, `review` FROM `yourtable` WHERE `review_id` = '$id'");

$row = mysql_fetch_assoc($query);
//$review_id = $row['review_id']; **You will not need this because you already have it in the URL
$title = $row['title'];
$review = $row['review'];
?>

<h1><?=$title?></h1><br /><br />
<p><?=$review?></p>

EDIT: Change:

$query = mysql_query("SELECT `review_id`, `title`, `review` FROM `reviews`");

To:

$query = mysql_query("SELECT `title`, `review` FROM `reviews` WHERE `review_id` = '".$_GET['id']."'");

Also... You will want to do some filtering on $_GET['id'] like:

preg_match('/^[0-9]{1,9}$/', $_GET['id'])

(Assuming your IDs are numbers)

Upvotes: 1

Related Questions