Reputation: 22395
Example:
$user_input = $_POST['input'];
'SELECT '.$user_input.' FROM table_name'
So it's selecting a column in a database based on a secure (this example isn't secure obviously) value. Is this practical/allowable code?
Upvotes: 0
Views: 62
Reputation: 15198
On it's face, this code is valid, assuming that $user_input
must be a valid column name, which means that it must exist and must not contain any special characters, reserved words, etc. (unless they're escaped).
As you said, however, this code isn't secure, but as long as you plan to build the query securely and use PDO or MySQLi (no deprecated mysql_*
functions...), you should be fine. If you need an example that doesn't use deprecated functions (including mysql_real_escape_string
, which is also being deprecated) I'll provide one.
I know you stated that you know this code isn't secure, but here's another example if you're curious. As was discussed in the comments and this question, this input:
$user_input = '; DELETE FROM table_name ; *';
'SELECT '.$user_input.' FROM table_name'
will delete the entire contents of the table table_name
. Even though this code raises a syntax error, MySQL will continue to execute it, thus effectively truncating table_name
.
Upvotes: 1
Reputation: 3058
In SQL you simply send a string
to the DBMS (like MySQL). Because of this you can build any string
you want and submit it to the DBMS.
You just have to make sure the resulting SQL query is valid. That means that e.g. the columns exist and that no invalid symbol appears.
Upvotes: 1