0

I've got a variable set at the top of my PHP:

$abc = "paid";

Now I need to pass it on to the below query as a column name. I tried the below but it did not work.

$sql = "SELECT customerID FROM payments WHERE :myVar = :credit";
$stmt = $connect->prepare($sql);
$stmt->execute(array(':credit'=>"0", ':myVar'=>$abc));

How do I pass $abc on to the select query as a column name?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Becky
  • 5,467
  • 9
  • 40
  • 73

2 Answers2

1

Curly brakets (from the PHP docs):

Complex (curly) syntax

This isn't called complex because the syntax is complex, but because it allows for the use of complex expressions.

Any scalar variable, array element or object property with a string representation can be included via this syntax. Simply write the expression the same way as it would appear outside the string, and then wrap it in { and }.

Your code should something like: "SELECT customerID FROM payments WHERE {$abc} = :credit";

Community
  • 1
  • 1
VladNeacsu
  • 1,268
  • 16
  • 33
  • thanks. Works fine :) But I'm a little confused after reading @Hexaholic comment. Any ideas? – Becky Jun 25 '15 at 08:53
  • @Hexaholic comment means you cannot bind column names like you do in `$stmt->execute(array(':credit'=>"0", ':$abc'=>$abc));`. But this solution will work, as my downvoted one è_é... – n00dl3 Jun 25 '15 at 09:04
-2

you cannot bind colname/table name in prepared queries, you could do like this:

$sql = "SELECT customerID FROM payments WHERE $abc=:credit";
$stmt = $connect->prepare($sql);
$stmt->execute(array(':credit'=>"0"));
n00dl3
  • 21,213
  • 7
  • 66
  • 76