0

I try to prepare statement to sql (mysqli) in php, but there is an error code as written above. This is the code I wrote:

 if (!$this->isUserExist($username, $token)) {return false;}
    $tables = array();        
    $tables[0] = "faculty";     
    $tables[1] = "department";  
    $tables[2] = "teacher";     
    $tables[3] = "announcement";
    $ttable = $tables[$table];
    var_dump($ttable); // faculty
    var_dump($id);     // 6
    echo "DELETE FROM ".$ttable." WHERE ".$ttable.".id = ".$id.""; //returns DELETE FROM faculty WHERE faculty.id = 6
    $stmt = $this->con->prepare("DELETE FROM ? WHERE ?.id = ?"); //Fatal error occurs here
    $stmt->bind_param("sss",$ttable,$ttable,$id);
    //$stmt->execute();
    if ($stmt->num_rows> 0) {
        return "true";
    } else {
        return "false";
    }

However if i insert exact statement without any placeholders that is shown in echo my i get no errors, and MySQL database successfully deletes row.

$stmt = $this->con->prepare("DELETE FROM faculty WHERE faculty.id = 6"); //no errors occur, executing this statement does affect row in MySQL database

2 Answers2

1

The system doesn't allow to 'prepare' table names, You should do it this way

$stmt = $this->con->prepare("DELETE FROM ".$ttable." WHERE ".$ttable.".id = ?"); //Fatal error occurs here
$stmt->bind_param("s",$id);
nacho
  • 5,280
  • 2
  • 25
  • 34
0

please read this http://us3.php.net/manual/en/book.pdo.php#69304

Table and Column names cannot be replaced by parameters in PDO.

Do something like this:

$query =  "DELETE FROM ".$ttable." WHERE ".$ttable.".id = ?";
$stmt = $this->con->prepare($query);
$stmt->bind_param("s",$id);
Ahmed Ginani
  • 6,522
  • 2
  • 15
  • 33