Can Prepared Statements Handle Dynamic Table Names?
You attempted to execute a MySQL prepared statement with a placeholder ? in the table name. Unfortunately , this is not a supported feature. Prepared statements are designed to bind parameters to "value" sections of an SQL statement, rather than structural elements such as table names.
At the database level, modifying the table name may change the validity of the statement, which is beyond the scope of precompilation. Even in database interfaces that allow placeholders to be used anywhere, the value of the placeholder is still converted to a string, so SELECT * FROM ? will actually send invalid SQL (i.e. `SELECT * FROM 'mytable' ' ).
The best practice to avoid this injection is to use whitelist checking. Before building the query, verify that the entered table name is in the pre-approved list. This will ensure that only safe table names are used, mitigating the risk of SQL injection.
The above is the detailed content of Can Prepared Statements Use Dynamic Table Names in SQL?. For more information, please follow other related articles on the PHP Chinese website!