Ok, so I have some PHP which passes a variable into the URL of a page. The PHP page picks up the variable named “item1”, it then adds a string to the front of the variable as follows (for examples sake lets say the variable is 10):
$v1 = $_GET['item1'];
echo "$v1";
$v2 = 'table-';
$v3 = $v2.$v1;
echo "$v3";
This prints “table-10” on the webpage. Brilliant.
Now I want to pass this into a MySQL select statement so it can query the table named “table-10”:
$sql = "select * from $v3";
$result = mysql_query ($sql);
However this does not work. Am I doing something really stupid here? Any help is appreciated.
Edit:
Thanks for all the help guys, with regards to SQLi injection your comments are appreciated however this is a local only system with no external exposure what so ever so any exploits are fairly unimportant as it stands. This system is only a proof of concept so when I actually build the full system I’ll make sure it doesn’t contain any exploits. The problem has been solved via the use of backticks so thanks very much!
Because the table name has a hyphen in it, you need to wrap it in backtick characters in the SQL string in order for mySQL to recognise it. eg:
Because you’re accepting part of the table name as a
$_GETvariable, it is vulnerable to SQL injection attacks. This means that a hacker could post a value to$_GET['item1']that includs other SQL commands, and execute those commands without you knowing. By doing this, it would be possible to find out any data he wanted from your database, and also to modify data.To avoid this, you need to “sanitise” the input. In your case, since you know the value should always be a number, it would be sufficient to force it to be an integer, and thus have it throw away any sneaky extra query data that a hacker might pass. eg:
(also note that if
item1isn’t passed at all, then PHP will throw a warning message when you try to reference it. I’ll ignore that for now, but you should probably fix that too)You haven’t given much info about your DB structure, but the hints given in the code you’ve supplied point toward a very poor database design. I won’t go into too much detail here beause it’s a big topic, but suffice to say that dynamic table names are usually a bad idea, as is a select without a
WHEREclause. AndSELECT *is also frowned upon in some circles, as it’s better to specify the fields explicitly (although*can be a helpful shortcut if you have a lot of fields).Finally, please avoid using the old
mysqlfunctions. They’re obsolete. Themysqlilibrary is very similar and easy to switch to. (If you’re reading tutorials based on the oldmysqlfunctions, then you should find some better tutorials!)