简体   繁体   中英

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

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

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

$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);
   ...
}

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";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM