1

All, I'm trying to write a mySQL query but PHP is giving me an error. The line that is giving me an error is:

$qry = "Select * from vendor_options where vendor_option_id='$_SESSION[pav_vendor_categories_$i]'";

The above code is in a for loop so that is how the $i is getting populated. The error I'm receiving is:

Parse error: syntax error, unexpected T_VARIABLE, expecting ']'

Any ideas on what is wrong? Thanks!

3
  • 2
    I will never understand why people construct their strings like that. Just concatenate or use sprintf! much tidier and cleaner. Commented Nov 29, 2011 at 14:15
  • repeated concatenation gets ugly quickly, and sprintf is far less readable in the long run. Commented Nov 29, 2011 at 14:34
  • How is sprintf less readable than doing, for example, what the OP has done? And what would you recommend to be the most readable of methods? curious.... Commented Nov 29, 2011 at 14:38

3 Answers 3

3
$sVendorId = $_SESSION['pav_vendor_categories_' . $i];
$sQuery = "SELECT * FROM vendor_options WHERE vendor_option_id='{$sVendorId}'";

This your working code.
Build vendor option ID outside of query — this will make you code more readable.

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

6 Comments

if it's an id, you don't need to wrap it with the apostrophes.
MySQL will ignore them :) but if vendor_option_id is a string value. but you didn't escape $sVendorId this is a problem.
I'd just cast the value to an integer, as a way of cleaning too.
if you sure that there will be only integer, than use intval() and remove quotes from query.
Just because MySQL will ignore it, doesn't mean it's a good idea. It's not good practice. I'd also be concerned if a field which has the word 'id' in it is a string type. But this wouldn't surprise me....
|
2

Try this;

$qry = "Select * from vendor_options where 
          vendor_option_id='{$_SESSION["pav_vendor_categories_{$i}"]}'";

Demo: http://codepad.org/0nHsFZ8i

Comments

0

should be :

$qry = "Select * from vendor_options where vendor_option_id='".$_SESSION["pav_vendor_categories_".$i]."'";

but dont do it like that... read about sql injection

hope this helps

3 Comments

pav_vendor_categories_$i will throw something. (error or a warning, not sure)
@Neal, no it doesn't. I've tested $i = 1;$_SESSION["foo1"] = "bar";echo $_SESSION["foo$i"]; it outputs "bar".. because it has double quotes =) anyway, it's kinda ugly so i've changed the code of my answer
you did not have the quotes there before.

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.