0

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.

Jose Borges
  • 340
  • 2
  • 4
  • 14
  • Can we see some more of your code around the SELECT and what is the return code telling you? – Dave Stokes Feb 09 '21 at 15:56
  • 2
    Please turn on [error reporting](https://stackoverflow.com/questions/1053424/how-do-i-get-php-errors-to-display) and share the actual error. Error 500 is just a generic error meant for users. – El_Vanja Feb 09 '21 at 16:22

1 Answers1

0

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);
Jose Borges
  • 340
  • 2
  • 4
  • 14