Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable table name in delete SQL query with PHP's PDO safely

I'm trying to create a function that allows me to delete a certain row in a table. I'd like to use the function for a few different tables so when I call the function I would make one of the parameters of the functions the table name. Here's an example of what I'm trying to do:

function delete($conn, $table, $id) {
    $stmt = $conn->prepare("DELETE FROM ".$table." WHERE id = :id");
    $stmt->bindParam(":id", $id, PDO::PARAM_INT);
    $stmt->execute();  

    if ($stmt->rowCount() > 0) {
            return true;
    } else {
            return false;
    }
}

One problem I'm having though is that because the $table variable goes straight into the SQL Query, wouldn't my database be under risk of SQL Injection?

As I learnt from one of my other questions, I can't just put :table and add it to the bindParam function, so I don't know how to make this function safe. Any ideas??

like image 775
Ben Avatar asked Apr 20 '26 21:04

Ben


1 Answers

Sanitize the table data

You can define an array of whitelisted table names to use in your function:

$whitelist = array('table1', 'table2', ...)

and then use:

$myTable= array_intersect_keys($table, array_flip($whitelist));

$myTable will now be safe.

like image 178
Jonathan Spiller Avatar answered Apr 24 '26 07:04

Jonathan Spiller