PHP using a variable in a mysql query with magic_quotes

178 Views Asked by At

I have a mysql query that uses a value in an array as part of the WHERE statement. How am I supposed to include this variable?

Here is the sql: "AND gender = '{$user_array[\"gender\"]}'"

PHP returns this error: Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING, expecting T_STRING

I have magic_quotes turned on. I've seen some posts suggesting setting the array's value to another variable, but seems unnecessary if I have magic quotes. Is this correct?

3

There are 3 best solutions below

8
Naftali On BEST ANSWER
"AND gender = '{$user_array['gender']}'"

It was the backslashes that were killing it.

Or you can even do:

"AND gender = '$user_array[gender]'"

Or:

"AND gender = '" . $user_array['gender'] ."'"

Demo: http://codepad.org/lrJllI1K

But all of this put together, you should be using prepared queries

1
Teena Thomas On

Just put the entire query in double quotes and then do like AND gender = '$user_array['gender']'

0
Jamesking56 On

As an alternative, you can do a string concat in PHP and keep your SQL in double quotes which may solve your issue:

"AND gender = '" . $user_array['gender'] . "'...