Php mysql WHERE子句错误

Can anyone see why this isn't working?

$category = 1;
$CategoryResult = mysql_query("SELECT * FROM Category WHERE Index = '$category'");
if (!$CategoryResult) 
    die("Could not retrieve results from category $category: " . mysql_error());

Mysql error as follows:

Could not retrieve results from category 1: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Index = '1'' at line 1

Index is an auto-increment primary key of the table Category.

This should be your code

$category = 1;
$CategoryResult = mysql_query("SELECT * FROM Category WHERE `Index` = $category");
if (!$CategoryResult) 
    die("Could not retrieve results from category $category: " . mysql_error());

Normally I would preach about mysql_real_escape_string, but if $category is under your control (such as from another query) - and it is guaranteed to be an int, then this code is safe.

  • Index is a reserved word - it must be backticked
  • Do not quote numerics. MySQL does has rules to convert (string) literals being compared to numbers, but unless you are familiar with the rules, just use proper numbers.

Example

select * from
(
select 1 `index`
union all
select 2
union all
select 3
) X
where `index` = '1-2-3-4'
   or `index` = '3.0Y!'

Output

`index`
1
3

maybe index is a reserved word . try this

$CategoryResult = mysql_query("SELECT * FROM Category c WHERE c.`Index` = '$category'");

and check if index is a string or an integer

Two problems I can see. If it is a primary key, you should be using WHERE Index = " . $category . ")

Secondly, Index is a reserved word in MySQL.

You should quote Index, as it's a MySQL keyword; like:

SELECT * FROM Category WHERE `Index` = $category;

And the single quotes are unnecessary and incompatible to ANSI SQL, assuming $category is numeric.