Dean
Dean

Reputation: 763

Display only queried ID+row PHP/MySQL

I have my data stored in a MySQL table, which includes an auto_increment ID number (unique) for each new row.

I'd like users to be able to get a certain ID number, using the $_GET function.

eg. User loads http://mysite.com/id.php?id=123
Page displays ID number 123 along with the row.

echo $row['id'];
echo "<table>";
echo "<tr> <th>Unit</th> <th>Message</th> <th>Date</th> </tr>";
while($row = mysql_fetch_array( $result )) {

echo "<tr><td>";
echo $row['title'];
echo "</td><td>";
echo $row['description'];
echo "</td><td>";
echo $row['pubDate'];
echo "</td></tr>";

}
echo "</table>";
echo "</center>";

I'm stuck as to where I put the $_GET bit.

Thanks :)

Upvotes: 0

Views: 1809

Answers (4)

Alex Pliutau
Alex Pliutau

Reputation: 21957

$id = $_GET['id'];
$id = mysql_real_escape_string($id);
$query = "SELECT * FROM `Table` WHERE `id`='" . $id . "'";
$res = mysql_query ($query);
$exist = mysql_num_rows($res);
if ($exist) {
   $row = mysqlfetch_assoc($res);
   ...
}

Upvotes: 0

Dan Hanly
Dan Hanly

Reputation: 7839

Dont waste your time doing the comparison afterwards, you'll save yourself alot of time by adding it to the original query

$id = intval($_GET['id']);
$query = "SELECT whatever FROM table WHERE id=$id";

Upvotes: 0

BMBM
BMBM

Reputation: 16013

You should append it to your query (using intval to avoid SQL injection) like this:

// use the id in your WHERE clause, convert it to an integer to avoid sql injections
$query = 'SELECT fields FROM table WHERE id = ' . intval($_GET['id']);

$result = mysql_query($query);
$row = mysql_fetch_row($result);

... do stuff with $row ...

Upvotes: 3

Mewp
Mewp

Reputation: 4715

Firstly, your code does not make much sense, since you use $row before it was defined.

Secondly, $result isn't defined at all, and it should be, for example like this:

$id     = intval($_GET['id']);
$result = mysql_query("SELECT FROM table WHERE id = '$id'");

And now you know how and where to use $_GET['id'].

Upvotes: 0

Related Questions