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.