LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   PHP/MySQL - Proper syntax for using alphabetical variables in a query? (https://www.linuxquestions.org/questions/programming-9/php-mysql-proper-syntax-for-using-alphabetical-variables-in-a-query-626904/)

win32sux 03-09-2008 10:07 PM

PHP/MySQL - Proper syntax for using alphabetical variables in a query?
 
I'm trying to use variables for a table and column name in a query, like:
Code:

$Table = "Products";
$Column = "Price";

$result = mysql_query("SELECT * FROM '$Table' ORDER BY '$Column'");
while($row = mysql_fetch_array($result))
  {
    // Stuff.
  }

It won't work, I get the ubiquitous error:
Code:

Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in...
I am able to use variables for numerical values without any problems (don't even need to use single quotation marks), but I can't figure-out how to make it so that I can use alphabetical values in queries such as the example I posted. Could you please show me the way? :newbie:

win32sux 03-09-2008 10:38 PM

Weird, I fixed some errors within the curly braces (// Stuff.) and it now works fine like:
Code:

$Table = "Products";
$Column = "Price";

$result = mysql_query("SELECT * FROM $Table ORDER BY $Column");
while($row = mysql_fetch_array($result))
  {
    // Stuff.
  }

:confused:

chrism01 03-10-2008 02:16 AM

Yeah, but notice you've removed the single-quote marks around the column names.
In many languages eg Shell, Perl, PHP, etc single-quote means DON'T interpolate the (apparent) value here, use this string as is.
You could use double-quotes, which DOES do interpolation, or not use quotes (as you have here).

win32sux 03-10-2008 06:37 AM

Thanks for the info. Weird thing is, I had indeed tried without any quotation marks at all too, and it wouldn't work either. Not sure if the error was the same, though. But once I fixed a couple problems with $row['blah'] things within the curly braces it worked (as it appears in my second post), so my guess is it had something to do with the curly brace content. Not sure if that makes sense, though. =/


All times are GMT -5. The time now is 04:40 PM.