1

I have a search program that has multiple input text boxes that correspond to fields in a mysql database. I would like to know if it is safe to have a custom search box where the user can enter the actual field to be searched and its value.

Like this:

<form method='post'>
 <input type='text' name='param1' />
 <input type='text' name='param2' />
 <input type='text' name='customField' />
 <input type='text' name='customValue' />
</form>

Then when it is submitted:

$param1 = mysql_real_escape_string($_POST['param1']);
$param2 = mysql_real_escape_string($_POST['param2']);
$customField = mysql_real_escape_string($_POST['customField']);
$customValue = mysql_real_escape_string($_POST['customValue']);

$query = "SELECT * FROM mytable WHERE field1 LIKE '" . $param1 . "' AND field2 LIKE '" . $param2 . "' AND " . $customField . " LIKE '" . $customValue . "'";

This is an internal webpage and only a few of us will actually see these new boxes but I would like to know if something like sql injection is possible here.

Mike
  • 2,862
  • 10
  • 42
  • 55

4 Answers4

5

You should check that the fields they provided are in a list/array of fields you allow searching within. Add backticks around the field names in the query just to be extra safe as well. Doing both those things will prevent any injection through those variables.

Dan Grossman
  • 51,866
  • 10
  • 112
  • 101
  • $whitelist = array('list','of','approved','column','names'); if(in_array($param1,$whitelist)) { execute query here... } – Bryan Feb 09 '11 at 14:25
1

You have to hardcode all possible wariants

See this my answer for example code: In PHP when submitting strings to the database should I take care of illegal characters using htmlspecialchars() or use a regular expression?

Community
  • 1
  • 1
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
0

I'd use PDO, just to be safe - then make sure you handle all errors accordingly.

Dave Kiss
  • 10,289
  • 11
  • 53
  • 75
0

Mike first of all disable the multiquery mode of your mysql and rest is fine,

And be aware of use of single table, if you are not using the joins then i do not there there will be any effect.

Ankur
  • 111
  • 8