views:

22

answers:

3

If I type

'

into my search bar I get a mysql error as the "sting" has not been escaped- it think.

But the reason why I cant escape it is because I dont think it currently is a string.

the search box generates search results dynamically with ajax it is as I type and it finds the results that I get the error:

    You have an error in your SQL syntax; check the manual that corresponds to
your MySQL server version for the right syntax to use near '%' OR Location
LIKE '%'%' OR Map LIKE '%'%' LIMIT 0, 16' at line 2

This is the mysql query:

<?php 
    if($_POST['q']!=""){
  include $_SERVER['DOCUMENT_ROOT'] . "/include/datebasecon.php";
        $result = mysql_query("
          SELECT id, Name, Location,  Map
          FROM Accommodation WHERE Name LIKE '%".$_POST['q']."%' OR Location LIKE '%".$_POST['q']."%' OR Map LIKE '%".$_POST['q']."%' LIMIT 0, 16") 
        or die(mysql_error());
        $output = "";
        while($row = mysql_fetch_array($result)){
            $N = preg_replace("/(".$_POST['q'].")/i","<span>$1</span>",$row['Name']);
            $L = preg_replace("/(".$_POST['q'].")/i","<span>$1</span>",$row['Location']);
            $M = preg_replace("/(".$_POST['q'].")/i","<span>$1</span>",$row['Map']);
            $output .= "<p>".$N." - ".$L."</p>";    
        }

        print $output;

    }
?>

Is there anyway i can fix this after its post the query maybe?

+3  A: 

When magic_quotes_gpc is off (as it should be!), $_POST['q'] is simply the string ', as just one character. That's why it's appearing in your SQL code like this:

%' OR Location LIKE '%'%' OR Map LIKE '%'%' LIMIT 0, 16

The error takes place at '%'%' because the LIKE string is being prematurely terminated.

You can just use mysql_real_escape_string() on $_POST['q'] and it'll be escaped:

$q = mysql_real_escape_string($_POST['q']);
$result = mysql_query("
  SELECT id, Name, Location,  Map
  FROM Accommodation WHERE Name LIKE '%".$q."%' OR Location LIKE '%".$q."%' OR Map LIKE '%".$q."%' LIMIT 0, 16") 
or die(mysql_error());
BoltClock
+1  A: 

You wrote "I dont think it currently is a string"... it is a string. You can pass it to mysql_real_escape_string() and use the result to make your query secure and reliable. Everything your script receives by the $_POST, $_GET, $_REQUEST and $_COOKIE params can be used as string, except it is an array.

hacksteak25
+1  A: 

To make you understand.
Look at your query:

LIKE '%search string%'

note apostrophes you have used to delimit search string.
These apostrophes does mean that data inside IS a string.
Everything you put in quotes into query is a string.
Everything you put in quotes into query must be escaped.
No need to think, consider or estimate. The rule is simple and unambiguous: quoted text should be always escaped.

Col. Shrapnel
Thank you for this, im fairly new to php, this has helped a lot
AJFMEDIA