Would this simple table name sanitisation be enough to prevent SQL injections?
$table = str_replace('`', '', $table);
$table = '`'.$table.'`';
Note: I use PDO.
Would this simple table name sanitisation be enough to prevent SQL injections?
$table = str_replace('`', '', $table);
$table = '`'.$table.'`';
Note: I use PDO.
If you are allowing the user to select which table they query from, the only way to "sanitize" and verify no hacking would be to have a whitelist of allowed tables. Your method would fail to allow for other database schemas also. This could also be as simple as querying for a list of tables from a specific database.
I don't have a mysql instance to play with to try to find bad table names. I can say though that while I can't think (or really test and verify) a way to bypass this, I can say that I can think of several ways that the query would straight up fail. Trying to access other databases otherDB.tableName or selecting from multiple tables with joins. While this would likely cause an error, you still don't want to take the chance of someone finding something that will go through.
If you want to be super safe, and avoid errors you could query the INFORMATION_SCHEMA to check if the table exists. Then you will know the tables exists, and can catch an invalid table earlier. You can also limit to a particular schema.
split the input into DB and Table (if necessary)
Select table_name, table_schema from information_schema.tables where table_schema = 'db' and table_name = 'tableName' (note: you can use parametrized query here to prevent injection)
If you get a return, might as well use the returned values (table_schema.table_name), else not a valid table
Then perform your query, knowing that the table exists, and is valid
This extra query of checking information_schema, could cause some overhead, but maybe you could optimize for your specific need.