0

I need help to make work this code:

<?php

$a = $_GET["a"];

$stmt = mysqli_stmt_init($conn);

if (mysqli_stmt_prepare($stmt,"SELECT * FROM `?`")) {

   mysqli_stmt_bind_param($stmt, "i", $a);
   mysqli_stmt_execute($stmt);
   $res = mysqli_stmt_get_result($stmt);

   while($row = mysqli_fetch_array($res)){
      if($row["id"] == 0){
         $title = $row["title"];
         $mal = $row["mal"];
      }
   }

   mysqli_stmt_close($stmt);
}

?>

In my DB I've some tables with numeric names (1,2,3...) and I want to get the table i want with the variable $a in the url.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
gianprito
  • 23
  • 4
  • _“and didn't find anythin searching online”_ - duplicate found by typing "prepared statements dynamic table name" into Google. – CBroe Dec 12 '17 at 15:13

1 Answers1

0

You cannot bind object names (a table name in this case) using prepared statements, only values. You'll have to resort to string manipulation (SQL sanitizing omitted for brevity's sake):

if (mysqli_stmt_prepare($stmt,"SELECT * FROM `$a`")) { # Here!

   mysqli_stmt_execute($stmt);
   $res = mysqli_stmt_get_result($stmt);
Mureinik
  • 297,002
  • 52
  • 306
  • 350