1

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?

5
  • 1
    can you show us a error part ? Commented Feb 16, 2019 at 3:16
  • 2
    You're not passing $table in recursiveDelete() when you do the call recursiveDelete($current['id'],$db_conn); Commented Feb 16, 2019 at 3:16
  • update my post. :) Commented Feb 16, 2019 at 3:19
  • 1
    @RenatoRamosPuma Well, you could try as a debug test echo "SELECT * FROM ".$table." WHERE Padre = '".$id."' " (optional . "<br>\n"); and that should be insightful. Commented Feb 16, 2019 at 3:20
  • @RenatoRamosPuma glad I could help. :) Commented Feb 16, 2019 at 4:29

1 Answer 1

3

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."' ");
}
Sign up to request clarification or add additional context in comments.

3 Comments

What I don't get is why doesn't it throw an error for not having enough arguments?
Master you have found the solution, thank you very much. :)
@Chipster PHP is permissive about incorrect argument number. I prints a warning, but doesn't throw an error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.