简体   繁体   English

如何使用PHP检索前导零的MySQL ID

[英]How to Use PHP to Retrieve MySQL IDs With Leading Zeros

I set up a new MySQL database and created some PHP Web pages. 我建立了一个新的MySQL数据库并创建了一些PHP网页。 The IDs for each entry are composed of three digits and have leading zeros (eg, 000, 001, 002). 每个条目的ID由三个数字组成,并带有前导零(例如000、001、002)。

My main page that shows every ID as a separate row in an HTML table works fine -- it displays every entry. 我的主页将每个ID作为单独的行显示在HTML表格中,可以正常工作-它显示每个条目。 But my individual entry page is not returning specific entries. 但是我的个人输入页面没有返回特定的输入。 For example, the URL entry.php?id=001 and entry.php?id=002 returns the entry for every ID. 例如,URL entry.php?id=001entry.php?id=002返回每个ID的条目。

I believe the error is at the beginning of the entry.php code, which looks like this: 我相信错误是在entry.php代码的开头,它看起来像这样:

$query = 'SELECT * FROM databasetablename';
if (isset($_GET['id']) && is_numeric($_GET['id']))
{
    $query .= ' WHERE id = ' . (int)$_GET['id'];  
}
$result = mysql_query($query);  

while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {

... and the code goes on. ...,代码继续。 But I think the error is in this part. 但我认为错误在于这部分。

您将$_GET['id']int之后$_GET['id'] = 1

I assume page IDs in database are not of a numeric type, but of CHAR/VARCHAR/TEXT. 我假设数据库中的页面ID不是数字类型,而是CHAR / VARCHAR / TEXT。 In this case you should try this: 在这种情况下,您应该尝试以下操作:

$query = 'SELECT * FROM databasetablename';
if (isset($_GET['id']) && is_numeric($_GET['id']))
{
    $query .= ' WHERE CAST(id AS INTEGER) = ' . (int)$_GET['id'];  
}
$result = mysql_query($query);

As a side note: consider using PDO with parameter binding instead of building queries directly from request parameters. 附带说明:考虑将PDO与参数绑定一起使用,而不是直接从请求参数构建查询。 This would be extremely dangerous : 这将是非常危险的

$query = ' WHERE CAST(id AS INTEGER) = ' . $_GET['id'];

EDIT: You could also try using mysql_real_escape_string() : 编辑:您也可以尝试使用mysql_real_escape_string()

$query .= ' WHERE id = ' . mysql_real_escape_string($_GET['id']);

but in this case you should read the security warning about character sets here: http://php.net/manual/en/function.mysql-real-escape-string.php 但是在这种情况下,您应该在此处阅读有关字符集的安全警告: http : //php.net/manual/en/function.mysql-real-escape-string.php

EDIT2: Sorry, I cannot write comments at the moment, but since you said that it returns every entry it could only mean that the WHERE condition is not added. EDIT2:对不起,我目前无法写评论,但是由于您说它返回了每个条目,因此只能表示未添加WHERE条件。 Check if you actually receive the "id" request parameter in entry.php by using var_dump($_GET) . 使用var_dump($_GET)检查在entry.php中是否实际收到“ id”请求参数。

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

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