PHP Mysql不接受表名称作为变量

时间:2019-02-16 03:13:35

标签: php mysql syntax var

mysql无法在函数的变量中识别我的表的名称,这是什么?

我的PHP代码:

$TableMaster = "table_name";
function recursiveDelete($id,$db,$table){
    $db_conn = $db;
    $query = $db->query("SELECT * FROM ".$table." WHERE Padre = '".$id."' ");
    if ($query->rowCount()>0) {
        while($current=$query->fetch(PDO::FETCH_ASSOC)) {
            recursiveDelete($current['id'],$db_conn);
        }
    }
    $db->exec("DELETE FROM ".$table." WHERE id = '".$id."' ");
}
recursiveDelete($_POST['id'],$db,$TableMaster);

错误PHP日志:

PHP Fatal error:  Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE Father = '99'' at line 1' in

注意:但是,当我直接在语句中写入mysql表的名称时,没有问题。

会发生什么事?

2 个答案:

答案 0 :(得分:3)

您在进行递归调用时忽略了$table参数。

也不需要$db_conn变量,只需使用$db

function recursiveDelete($id,$db,$table){
    $query = $db->query("SELECT * FROM ".$table." WHERE Padre = '".$id."' ");
    if ($query->rowCount()>0) {
        while($current=$query->fetch(PDO::FETCH_ASSOC)) {
            recursiveDelete($current['id'],$db,$table);
        }
    }
    $db->exec("DELETE FROM ".$table." WHERE id = '".$id."' ");
}

答案 1 :(得分:0)

尝试使用带有设置器的prepareexecute_query代替queryexec,这样更干净。