0

I'm trying to use prepare statements in an SQL query, but I'm having trouble when there is a variable in select.

This doesn't work properly:

$variable = "username";
$userId = "157";

$stmt = $conn->prepare("SELECT ?
                        FROM myTable
                        WHERE id=?");
$stmt->bind_param("ss", $variable, $userId);
$stmt->execute();
$stmt->bind_result($result);
$stmt->fetch();
printf("ID: %s and %s is: %s\n", $userId, $variable, $result);

It prints "ID: 157 and username is: username" when it's supposed to print something like "ID: 157 and username is: john90"

I'm guessing that the problem is that I'm using variables in the SELECT part of the query, but I can't remove this variable because sometimes I require different content, not just username. (Some times the variable could be email or age or etc).

Any suggestions appreciated.

Cait
  • 61
  • 6
  • 2
    You can't bind column names or table names. – aynber Apr 03 '17 at 18:36
  • Also, when I don't use prepare statement to execute the query, it works fine for some reason that I don't know... – Cait Apr 03 '17 at 18:36
  • How can MYSQL compile,optimise and prepare an execution plan if it does not know what columns you want to be returned from the query – RiggsFolly Apr 03 '17 at 18:40

0 Answers0