[英]PHP query with variable of table's name of MySQL
I'm having a problem to get a query that the name of the table is a php variable sent by javascript Ajax.我在查询表的名称是 javascript Ajax 发送的 php 变量时遇到问题。 I tried:我试过了:
"SELECT * FROM `$tablename`"
"SELECT * FROM ".$tablename
"SELECT * FROM '$tablename'"
Even with hardcoded as:即使硬编码为:
"SELECT * FROM `tablename`"
"SELECT * FROM tablename"
"SELECT * FROM 'tablename'"
Nothing is working to get the query.没有任何方法可以获取查询。
This is the full PHP query:这是完整的 PHP 查询:
$tablename= "tablename";//$_POST["tablename"];
//tried also this $tablename = sprintf($tablename);
$sql = "SELECT * FROM $tablename";
$result = mysqli_query($conn, $sql);
echo $result; //To check if there was a result
$rows_result = null;
while($r_result = mysqli_fetch_assoc($result)) {
$rows_result[] = $r_result;
}
mysqli_close($conn);
Some of the tries I did as above gave me page error - code 500, others just gave a blank page.我上面所做的一些尝试给了我页面错误 - 代码 500,其他人只是给了一个空白页。
I tried to load directly the.php page.我尝试直接加载.php 页面。 And in another.php when I want to create the table I simply put "CREATE TABLE IF NOT EXISTS $tablename...", and it works fine.在另一个.php 中,当我想创建表时,我只需输入“CREATE TABLE IF NOT EXISTS $tablename ...”,它工作正常。
Finally got it working like this:最后让它像这样工作:
$tablename= $_REQUEST["tablename"];
$sql = "SELECT * FROM `$tablename`";
$result = $conn->query($sql);
$rows_result = null;
while($r_result = mysqli_fetch_assoc($result)) {
$rows_result[] = $r_result;
}
echo json_encode($rows_result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.