This question already has answers here:
Can I parameterize the table name in a prepared statement?
(2个答案)
去年关门了。
所以我遇到了一些背道而驰的事情,我真的不知道为什么。当我运行原始代码时,会收到一条错误消息,说我的查询不可接受。
所以我的代码如下。
所以这会导致
但是,当我做下面的事情时,它运行良好。
所以这是我这边的错误还是我不能用参数作为表?。我更希望将表作为准备好的语句参数加载,但如果无法围绕它,我将不得不随机应变。
(2个答案)
去年关门了。
所以我遇到了一些背道而驰的事情,我真的不知道为什么。当我运行原始代码时,会收到一条错误消息,说我的查询不可接受。
所以我的代码如下。
$parts = array(
"engine",
"reactor"
);
$count = count($parts);
for($x = 0; $x < $count; $x++) {
$table = 'ship_'.$parts[$x];
$sql = "SELECT * FROM ? WHERE UserId = ?";
$stmt1 = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt1,'si',$table, $n_userid)
.....
所以这会导致
Fatal error: Wrong SQL: SELECT * FROM ? WHERE UserId = ? Error: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '? WHERE UserId = ?'
但是,当我做下面的事情时,它运行良好。
for($x = 0; $x < $count; $x++) {
$table = 'ship_'.$parts[$x];
$sql = "SELECT * FROM ". $table ." WHERE UserId = ?";
$stmt1 = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt1,'i', $n_userid);
....
所以这是我这边的错误还是我不能用参数作为表?。我更希望将表作为准备好的语句参数加载,但如果无法围绕它,我将不得不随机应变。
最佳答案
无法对表名使用绑定参数。
只能通过绑定占位符提供值。
标识符(表名、列名、函数名等)不能通过绑定占位符提供。