我有一个应用程序,它为我的PHP传递一个变量(nomecardapioBD并且接收并记录在变量:nomecardapioBD中),这是我想要选择所有行和列的表名。
但是通过帖子接收变量无法进行预约。谁能告诉我这部分代码有什么问题?
$query = "Select * FROM :nomecardapioBD ";
$query_params = array(
':nomecardapioBD' => $_POST['nomecardapioBD']
);
//execute query
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt->fetchAll();
答案 0 :(得分:3)
为什么不呢?
$query = "Select * FROM " . $_POST['nomecardapioBD'];
//execute query
try {
$stmt = $db->prepare($query);
$result = $stmt->execute();
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt->fetchAll();
您也应该进行某种输入清理。
答案 1 :(得分:2)
表和列名称不能由PDO中的参数替换。只需将其用作
即可$table=$_POST['nomecardapioBD'];
$query = "Select * FROM $table";
//execute query
try {
$stmt = $db->prepare($query);
$result = $stmt->execute();
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}