我尝试在php中为sql(mysqli)准备语句,但是上面有一个错误代码。这是我写的代码:
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";
}
但是,如果我插入确切的语句没有任何占位符,在echo我显示没有错误,MySQL数据库成功删除行。
$stmt = $this->con->prepare("DELETE FROM faculty WHERE faculty.id = 6"); //no errors occur, executing this statement does affect row in MySQL database
答案 0 :(得分:0)
系统不允许准备'表名,你应该这样做
$stmt = $this->con->prepare("DELETE FROM ".$ttable." WHERE ".$ttable.".id = ?"); //Fatal error occurs here
$stmt->bind_param("s",$id);
答案 1 :(得分:0)
请阅读此http://us3.php.net/manual/en/book.pdo.php#69304
表和列名称不能替换为PDO中的参数。
做这样的事情:
$query = "DELETE FROM ".$ttable." WHERE ".$ttable.".id = ?";
$stmt = $this->con->prepare($query);
$stmt->bind_param("s",$id);