简体   繁体   English

SELECT id WHERE id等于传递的值

[英]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: 我通过以下方式将“id”值从一个页面media_main.php传递给另一个player.php:

<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. 在player.php页面上,我想选择某些数据,其中id等于传递的id。 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. 我不知道如何处理WHERE子句,因为它将更改而不是静态数字。 I only want to select the data when the id to equal the passed id value. 我只想在id等于传递的id值时选择数据。

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: 从代码的外观来看,您通过URL参数( pid )传递ID,在这种情况下,您只需要转义字符串以防止SQL注入并使用结果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. 此外,如果id是主/唯一键,那么您可以从查询中删除ORDER BY子句,因为它没有任何区别。

EDIT The answer has been updated as suggested in the comments below to include quotes around the SQL argument. 编辑答案已按照以下评论中的建议进行了更新,以包含SQL参数的引号。

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. 除了Clive的响应,如果您知道ID只是数字,您可以将其转换为Integer而不是转义它。

If there is any erroneous input it will just cast it to 0. 如果有任何错误输入,它只会将其转换为0。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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