How do I use PHP variables as field names in a MySQL query?

For example:

{$fieldname = "mygreatfield"}

My current query is:
$query = "SELECT mygreatfield FROM mytable WHERE id=3";

In the query, what is the syntax for replacing "mygreatfield" with the value in $fieldname.

Keep in mind that the $query is already inside <?php  ... ?> tags, so trying to just insert an echo doesn't look right to me, so I didn't even attempt it.

High points on this cause I'm working on a deadline and need an answer fast.
alicia1234Asked:
Who is Participating?
 
Guy Hengel [angelIII / a3]Connect With a Mentor Billing EngineerCommented:
$query = "SELECT {$fieldname} FROM mytable WHERE id=3";
0
 
Guy Hengel [angelIII / a3]Billing EngineerCommented:
or
$query = "SELECT `" . $fieldname . "` FROM mytable WHERE id=3";
resp:
$query = "SELECT `{$fieldname}` FROM mytable WHERE id=3";

Open in new window

0
 
alicia1234Author Commented:
How nice that it's that simple. I should have realized it because I do the same thing for the values. For some reason, I guess I just thought that field names would work differently.
Thanks!

0
Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

 
Guy Hengel [angelIII / a3]Billing EngineerCommented:
glad I could help.
note that you are aware of the difference of the quotes (') for the string values vs the backticks (`) for the table/column names.
0
 
alicia1234Author Commented:
Should this same syntax work for POST vars? Like this:

$lastfname = "staples"
if ( isset($_POST['{$lastfname}']) ....

because it doesn't see to be working
0
 
Guy Hengel [angelIII / a3]Billing EngineerCommented:
you put {} where you don't need them


if ( isset($_POST[$lastfname]) ....

Open in new window

0
 
alicia1234Author Commented:
Thanks! Again ... ;-)

0
All Courses

From novice to tech pro — start learning today.