1

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.

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

1 Comment

This is probably it. index is a very bad column name, I would change it.
2

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

2 Comments

Your last statement is incorrect. MySql will convert it to a number.
@The Scrum Meister - You are right. I updated the answer to make it a warning/recommendation instead.
1

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.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.