The level of protection you are looking for is provided by backticks :
"SELECT * FROM `$db` WHERE 1";
Backticks are used to qualify identifiers that might otherwise be ambiguous (e.g. MySQL reserved words ), and if you accept user input or have columns or bases with a variable name, you absolutely must use backlinks, or I can promise that You will run into problems in the future. For example, what if you had a system in which a temporary field name was created with some user input, only it turned out that the field received the name update ?
"SELECT field1,field2,update FROM table;"
He is failing. But:
"SELECT `field`,`field2`,`update` FROM table"
works just fine. (This is really a real example from a system that I worked on several years ago that had this problem).
This solves your problem in terms of entering bad SQL. For example, the following query simply returns an “unknown column” error, where test; DROP TABLE test test; DROP TABLE test - code of the introduced attack:
"SELECT * FROM `test; DROP TABLE test`;"
Be careful: SQL injection is still possible with backticks!
For example, if your $db variable contains data that had a downside in it, you can still add some SQL in normal mode. If you use variable data for the database name and fields, you must strip it of all backreferences before placing it in your statement, and then adjust it with the inverse conclusions once inside.
$db = str_replace('`','',$db); $sql = "SELECT * FROM `$db` WHERE 1";
I use a database shell that has separate functions for disinfecting data and disinfecting database identifiers, and this is what the latter do :)