Jump to content


Photo

Using a PHP variable in an MySQL query


  • Please log in to reply
3 replies to this topic

#1 nickholt1972

nickholt1972
  • Members
  • PipPipPip
  • Advanced Member
  • 30 posts
  • LocationBury, Lancs, UK

Posted 07 October 2006 - 08:50 PM

I've posted this in the MySQL forum, but it could be in either and this one has more traffic.

I want to select items from my database where the id for the record is equal to the PHP variable being passed from the previous page. In theory the code should look something like...

$productdetails = @mysql_query('SELECT * FROM stocks WHERE id = $_SESSION['cart'][$i]');

But I don't seem to be able to use a variable in a query.

Does anyone know of an alternative method for getting round this problem?

Thanks,

Nick
Nick Holt - Future Guru

#2 Orio

Orio
  • Staff Alumni
  • Advanced Member
  • 2,491 posts

Posted 07 October 2006 - 08:52 PM

You should add single qoutes around it:
SELECT * FROM stocks WHERE id = '$_SESSION['cart'][$i]'

Orio.
Think you're smarty?

(Gone until 20 to November)

#3 nickholt1972

nickholt1972
  • Members
  • PipPipPip
  • Advanced Member
  • 30 posts
  • LocationBury, Lancs, UK

Posted 07 October 2006 - 09:12 PM

That's great, thanks. only problem is, I can't surround the variable with single quotes because i've got singles at the start and end of the SELECT statement. I can't change those to doubles or use doubles to surround the variable because i get error messages. And i can't escape them either.

I appreciate your help.
Nick Holt - Future Guru

#4 shiny_spoon

shiny_spoon
  • Members
  • PipPip
  • Member
  • 26 posts
  • LocationCanada

Posted 07 October 2006 - 09:55 PM

Try this:

'SELECT * FROM stocks WHERE id = '.$_SESSION['cart'][$i].' '

or
'SELECT * FROM stocks WHERE id = "'.$_SESSION['cart'][$i].'" '


Edit: For the record, I'm quite sure that to use a variable directly in a query without concating, you would have to declare it like so:
$var = $_SESSION['cart'][$i];
and then use the variable in double quotes:
'SELECT * FROM stocks WHERE id = "$var" '





0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users