I am trying to query the data in a column dependent on the variable $garment. The query works until I try to bind the parameter $garment . Any idea what I'm doing wrong?
Thanks!
//THIS WORKS
if ($stmt = mysqli_prepare($mysqli, "SELECT $garment FROM user WHERE uid=?")) {
mysqli_stmt_bind_param($stmt, "i", $uid);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $total);
mysqli_stmt_fetch($stmt);
mysqli_stmt_close($stmt);
}
//DOESN'T WORK - $total returns the value of $garment
if ($stmt = mysqli_prepare($mysqli, "SELECT ? FROM user WHERE uid=?")) {
mysqli_stmt_bind_param($stmt, "si", $garment, $uid);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $total);
mysqli_stmt_fetch($stmt);
mysqli_stmt_close($stmt);
}
That happens because with prepared statements you only can build values (not identifiers). That's it
becomes
The first code is the correct one but to be safe you must ensure that the
$garment
variable value is whitelisted.You can't use markers for the column name. So you'll have to specify the actual column name w/o a marker.
From the official php docs