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??
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With