Can I parameterize the table name in a prepared statement?

前端 未结 2 1100
萌比男神i
萌比男神i 2020-11-21 05:03

I\'ve used the mysqli_stmt_bind_param function several times. However, if I separate variables that I\'m trying to protect against SQL injection I run into errors.

H

2条回答
  •  执笔经年
    2020-11-21 06:00

    Short answer to your question is "no".

    In the strictest sense, at the database level, prepared statements only allow parameters to be bound for "values" bits of the SQL statement.

    One way of thinking of this is "things that can be substituted at runtime execution of the statement without altering its meaning". The table name(s) is not one of those runtime values, as it determines the validity of the SQL statement itself (ie, what column names are valid) and changing it at execution time would potentially alter whether the SQL statement was valid.

    At a slightly higher level, even in database interfaces that emulate prepared statement parameter substitution rather than actually send prepared statements to the database, such as PDO, which could conceivably allow you to use a placeholder anywhere (since the placeholder gets replaced before being sent to the database in those systems), the value of the table placeholder would be a string, and enclosed as such within the SQL sent to the database, so SELECT * FROM ? with mytable as the param would actually end up sending SELECT * FROM 'mytable' to the database, which is invalid SQL.

    Your best bet is just to continue with

    SELECT * FROM {$mytable}
    

    but you absolutely should have a white-list of tables that you check against first if that $mytable is coming from user input.

提交回复
热议问题