Prevent MySQL Injection on search and dropdowns
Hey all, I know this might have been asked before but I am trying to protect my search field and drop downs from MySQL injection and am having trouble integrating mysql_real_escape_string into my PHP. I am currently filtering my search results by keywords in 2 drop downs or by a freeform input where the user types in a reference. I've commented below where I am trying to add the escape string but it is breaking my search function. Can anyone advise me on what to do? Thanks for any help
// SEARCH FROM TEXT INPUT
$searchword = $_POST['searchByRef'];
//ESCAPE STRING HERE
$searchword = mysql_real_escape_string($connectInfo, $searchword);
$query_dbname = "SELECT * FROM dbname WHERE `ref` LIKE '%".$searchword."%'";
// SEARCH FROM DROPDOWN MENUS
$drop1 = $_POST['search1'];
$drop2 = $_POST['search2'];
//ESCAPE STRING HERE
$drop1 = mysql_real_escape_string($connectInfo, $drop1);
$drop2 = mysql_real_escape_string($connectInfo, $drop2);
$query_dbname = 'SELECT * FROM dbname WHERE 1=1' . ($drop1 ? ' AND `colour` LIKE "%' . $drop1 . '%"' : '') . ($drop2 ? ' AND `style` LIKE "%' . $drop2 . '%"' : ' ORDER BY id DESC');
$query_dbname = "SELECT * FROM dbname ORDER BY ref DESC";
$dbname = mysql_query($query_dbname, $connectInfo) or die(mysql_error());
$row_dbname = mysql_fetch_assoc($dbname);
$totalRows_all = mysql_num_rows($dbname);
Looks like you have the arguments reversed when you call mysql_real_escape_string. The first arg is the string to be escaped, and the 2nd is the (optional) connection identifier.
Of course, you could quit using the now-deprecated MySQL extension and instead either use the MySQLi extension or PDO extension, allowing you to make use of prepared statements with bound parameters, letting them take care of any needed escaping automatically.
"Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
~ Terry Pratchett in Nation
Users Browsing this Thread
There are currently 1 users browsing this thread. (0 members and 1 guests)