Securely escaping dynamic table names in MySQL using Codeigniter Securely escaping dynamic table names in MySQL using Codeigniter codeigniter codeigniter

Securely escaping dynamic table names in MySQL using Codeigniter


The escaping mechanisms are only for data strings, not for schema names. In other words, only for the content of a table, not for its structure. So you'll either have to paste the string into the query yourself, or avoid using tables in this way. The ? of query templates won't help you there.

If you paste the string into the table name, you can use the usual PHP string concatenation mechanisms. You should make extra sure that you check the string against a suitably strict regular expression, to avoid SQL injection. Make sure that you really only paste a single random string of the format you generate, and nothing else.

As an alternative, you could have one big table, containing all the selections, and use an additional column to hold your identification hash, or some other suitable key to identify a single selection. That way, you wouldn't have to modify the database schema during normal operations. I believe most developers, me included, would rather avoid such modifications by program code. Good database design works with a fixed schema.


It sounds to me like you want to use dynamic SQL. You'll probably have to go down the path of prepared statements. With them, you can call PREPARE on the string and subsequently EXECUTE it. Normal concatenation works just fine.

That should allow you to build your SQL as a string and execute it. If you use CodeIgniter's parametrization in combination with MySQL stored procedures, you can call a query like "CALL selectAlbums(?, ?)" (assuming selectAlbums is the stored procedure containing the PREPARE for the actual query), which will return the set.

If you want to get rid of the 's in output, channel the parameters through CONCAT, which will produce a normal string.