0

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

    <?php 
    // SEARCH FROM TEXT INPUT 
    mysql_select_db($database_connectInfo, $connectInfo); 
    if (isset($_POST['searchByRef'])) 

     {     
          $searchword = $_POST['searchByRef']; 

    //ESCAPE STRING HERE 
    $searchword = mysql_real_escape_string($connectInfo, $searchword); 

    $query_dbname = "SELECT * FROM dbname WHERE `ref` LIKE '%".$searchword."%'"; 
} 

    else 

    // SEARCH FROM DROPDOWN MENUS 

    if (isset($_REQUEST['submit'])) 
    {    
        $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');    
} 
else 

{ 
    $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); 
?>
Richard
  • 1
  • 1

1 Answers1

0

Don't use mysql_escape_string.. instead use mysqli or PDO with prepared statements.

http://www.php.net/manual/en/book.pdo.php

For more info on WHY see this:

Why mysql_real_escape_string() did not prevent hack?

Community
  • 1
  • 1
Zak
  • 24,947
  • 11
  • 38
  • 68