简体   繁体   中英

How to Use PHP to Retrieve MySQL IDs With Leading Zeros

I set up a new MySQL database and created some PHP Web pages. The IDs for each entry are composed of three digits and have leading zeros (eg, 000, 001, 002).

My main page that shows every ID as a separate row in an HTML table works fine -- it displays every entry. 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.

I believe the error is at the beginning of the entry.php code, which looks like this:

$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. 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. This would be extremely dangerous :

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

EDIT: You could also try using 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

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. Check if you actually receive the "id" request parameter in entry.php by using var_dump($_GET) .

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