tags:

views:

31

answers:

4

Hi,

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 :)

+2  A: 

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 ...
Max
btw - intval is weird: `echo intval(array('foo', 'bar')); // 1` - what???
Dominic Rodger
@Dominic Rodger PHP is (sometimes) weird ;). Thanks for the edit!
Max
Great, thanks :)Full code if anyone ever wants it: http://codepad.org/H3l5RtrV
Dean
@Dean - you're still using `$row` before it's set (you use it on line 14, it's set on line 17).
Dominic Rodger
A: 

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'].

Mewp
I only put in a snip of it, it's defined earlier.
Dean
A: 
$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);
   ...
}
Alexander.Plutov
`yourpage.com?id='; DELETE * FROM Table; SELECT * FROM Table WHERE id='3`
Dominic Rodger
This query will not work, because data and fields are escaped.
Alexander.Plutov
@Alexander - they are now!
Dominic Rodger
A: 

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";
Daniel Hanly
Yeah, that's what I thought. Couldnt work out how to put it in there though.Thanks for the elaboration.
Dean