简体   繁体   中英

SELECT id WHERE id equals a passed value

I am passing the "id" value from one page media_main.php to another player.php via:

<a href="javascript:;" onclick="return popitup('player.php?pid=<?php echo ("$row->id");?>')" title="Listen">

On the player.php page I would like to select certain data WHERE the id equals that id that was passed. So far I have this:

$query = "SELECT id, media_date, media_title, given_by, filename FROM media WHERE id = ?? ORDER BY id DESC";

I'm not sure how to work the WHERE clause since it will change and not be a static number. I only want to select the data when the id to equal the passed id value.

From the looks of your code you're passing the ID in via a URL parameter ( pid ), in which case you just need to escape the string to prevent SQL injection and build your query up using the resulting id:

$pid = mysql_real_escape_string($_GET['pid']);

$query = "SELECT id, media_date, media_title, given_by, filename FROM media WHERE id = '$pid' ORDER BY id DESC";

It would probably be wise to check that the passed value is numeric.

Also, if id is a primary/unique key then you can remove the ORDER BY clause from the query as it will make no difference.

EDIT The answer has been updated as suggested in the comments below to include quotes around the SQL argument.

Additionally to Clive's response, if you know that the ID is only numerical, you can cast it to an Integer instead of escaping it.

If there is any erroneous input it will just cast it to 0.

$pid = (int) $_GET['pid'];

$query = "SELECT id, media_date, media_title, given_by, filename FROM media WHERE id = '$pid' ORDER BY id DESC";

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