![]() |
Escaping Variables / Arrays in MySQL Strings
Okay so I am currently attempting to make a mock-up of an eCommerce site and I noticed that on more than one occasion I have had issues trying to figure out the correct syntax for using arrays (multi-dimensional or otherwise) within MySQL query strings. Specifically the use of quotes (single or double) causes some confusion for me.
I want to put together a cart in the $_SESSION namespace that should have this form: $_SESSION['cart']['item_' . $n], where $n starts from 0 and increases by one during every instance of the loop. For every 'item_n' there will be an associated 'item_n_qty' that holds the associated quantity in the cart for each item. If I wanted to include this multi-dimensional array in a MySQL query, what is the best way to do this? Currently I have the following: PHP Code:
|
Okay so I figured out the problem. Apparently I have to use the curly braces around the entire $_SESSION variable. My final string that worked is as follows:
PHP Code:
|
Thanks for sharing. We can also solve it by using concatenation operator like so..
PHP Code:
|
Yep, in double quotations if you have a complex type you should use braces around them. A single dimension won't require them, but multiple dimensions will as the parser is ungreedy within the double quotes. So it would resolve first $_SESSION['cart'], then take the result (which is Array) and offset the [$index]. So it attempts to write it as
Array[$index] which of course will not dereference to any valid value as its not a variable. The alternative above is the approach I would use, although typically I just use printformatting so I don't need to string concat. Another alternative is to use prepared statements and bind the variables. |
| All times are GMT +1. The time now is 10:30 AM. |
Powered by vBulletin®
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.