Can I query a DB, using a variable for the fieldname?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
simonmlewis
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

Can I query a DB, using a variable for the fieldname?

Post by simonmlewis »

Code: Select all

if (isset($rc))
{
  echo "<div class='product_pricebox_details'><form method='post' action=''>
  <input type='hidden' name='romancode' value='$romancode'>";
  $romancoderc = "$romancode"."$rc";
  echo "$romancode";
    $queryrc = ("SELECT * FROM products WHERE $romancoderc :=romancode");
    $resultrc = $pdo->prepare($queryrc);
    $resultrc->execute(array(':romancode' => $romancode));
    while ($rowrc = $resultrc->fetch(PDO::FETCH_OBJ)) 
      {  
      
  echo "$rowrc->title";
  }
  
  echo "<input type='submit' value='Buy Now'>
  </form></div>";
}
I have 9 codes to query, but only one is posted. So in the URL I am sending thru which number of code is sent, and the code itself.

So $row->romancode3 is posted through, as $romancode, and /3/ is in the URL.
So in the next page I can pop '3' on the end. Saves having 9 lots of code (as this code will get longer).

I want to query either romancode1, romancode2... 9 in the script. So how do I use this to query only one of those fields.
What I am doing isn't causing errors, but it's not doing anything either?!

$rc is 1 ..... 9 .
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
Post Reply