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:48 PM

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 printf

printf
  • Staff Alumni
  • Advanced Member
  • 889 posts

Posted 07 October 2006 - 09:11 PM

Enclose {$var} or dot ' . $var . '...

example (1)

// enclose method

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

example (2)

// dot method

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

Notice on the right side of the variable, there is no * . ' *, because it isn't needed when a variable beigins or ends a function(s) param value or a echo and print statement or any $varible assignment!

me!



#3 nickholt1972

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

Posted 07 October 2006 - 09:21 PM

Thanks man, you have no idea how long i've been fighting with that particular beast.

Nick
Nick Holt - Future Guru

#4 fenway

fenway
  • Staff Alumni
  • MySQL Si-Fu / PHP Resident Alien
  • 16,199 posts
  • LocationToronto, ON

Posted 09 October 2006 - 05:47 AM

To be clear, PHP can't guess how much of your "complex" variable name is really "there" unless you make it explicit.
Seriously... if people don't start reading this before posting, I'm going to consider not answering at all.




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users