• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 367
  • Last Modified:

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.
0
alicia1234
Asked:
alicia1234
  • 4
  • 3
1 Solution
 
Guy Hengel [angelIII / a3]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 your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

 
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

  • 4
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now