Renato Ramos
Renato Ramos

Reputation: 429

PHP Mysql does not accept table name as variable

mysql does not recognize the name of my table in a variable in a function, what can it be?

My PHP Code:

$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);

ERROR PHP LOG:

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

Note: But when I write the name of my mysql table directly in the statement there is no problem.

Whats happen?

Upvotes: 1

Views: 360

Answers (1)

Barmar
Barmar

Reputation: 782624

You left out the $table argument when making the recursive call.

There's also no need for the $db_conn variable, you can just use $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."' ");
}

Upvotes: 3

Related Questions