Mysqli SELECT ? (bind_param)

2019-03-02 20:23发布

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);
}

标签: php mysqli
2条回答
霸刀☆藐视天下
2楼-- · 2019-03-02 21:06

That happens because with prepared statements you only can build values (not identifiers). That's it

SELECT ? 

becomes

SELECT 'somevalue'

The first code is the correct one but to be safe you must ensure that the $garment variable value is whitelisted.

查看更多
劳资没心,怎么记你
3楼-- · 2019-03-02 21:12

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

The markers are legal only in certain places in SQL statements. For example, they are allowed in the VALUES() list of an INSERT statement (to specify column values for a row), or in a comparison with a column in a WHERE clause to specify a comparison value.

However, they are not allowed for identifiers (such as table or column names), in the select list that names the columns to be returned by a SELECT statement), or to specify both operands of a binary operator such as the = equal sign. The latter restriction is necessary because it would be impossible to determine the parameter type. In general, parameters are legal only in Data Manipulation Languange (DML) statements, and not in Data Defination Language (DDL) statements.

查看更多
登录 后发表回答