If you have to let the attacker control a direct substring of SQL, then use a whitelist of allowed characters – for tablenames, [a-zA-Z0-9_] is usually good enough, and then put that in quotes (as some databases reserve keywords such as "user" or "password", which is bad if you want to name columns like that).
I’ve had quite a few codebases I’ve worked on where I had to replace naive code [1], and until now, it’s always been easily possible to ensure that the entire space of possible inputs is limited enough to prevent SQL injections.
Sure, there are rare projects where you have to do such very complicated systems, but for 99%, it’s possible to get guaranteed protection from SQL injections.
________________________
1: "db->query('SELECT 1 FROM users WHERE username = "' + $_POST['username'] + '" AND password = "' + md5($_POST['password']) + ';"');" was real code I’ve seen
I’ve had quite a few codebases I’ve worked on where I had to replace naive code [1], and until now, it’s always been easily possible to ensure that the entire space of possible inputs is limited enough to prevent SQL injections.
Sure, there are rare projects where you have to do such very complicated systems, but for 99%, it’s possible to get guaranteed protection from SQL injections.
1: "db->query('SELECT 1 FROM users WHERE username = "' + $_POST['username'] + '" AND password = "' + md5($_POST['password']) + ';"');" was real code I’ve seen