简体   繁体   中英

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. 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:

$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.

I tried to load directly the.php page. And in another.php when I want to create the table I simply put "CREATE TABLE IF NOT EXISTS $tablename...", and it works fine.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM