Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Is the code below safe from SQL injection?

<?

mysql_connect ("localhost", "db","pass")  or die (mysql_error());
mysql_select_db ("db");

$term = mysql_real_escape_string($_POST['term']);

$sql = mysql_query("select * from tblListings where category like '%$term%' or title like '%$term%' or postcode like '%$term%' or info like '%$term%' ");

function highlight($needle, $haystack)
{
    return preg_replace('/(' . preg_quote($needle, '/') . ')/i', '<mark>$1</mark>', $haystack);
}

while ($row = mysql_fetch_array($sql)){

    echo '<br/> Category: ' . highlight($term, $row['category']);
    echo '<br/> Title: ' . highlight($term, $row['title']);
    echo '<br/> Address: ' . highlight($term, $row['add1']);
    echo '<br/> Street: ' . highlight($term, $row['street']);
    echo '<br/> City: ' . highlight($term, $row['city']);
    echo '<br/> Postcode: ' . highlight($term, $row['postcode']);
    echo '<br/> Phone: ' . highlight($term, $row['phone']);
    echo '<br/> E-Mail: ' . highlight($term, $row['email']);
    echo '<br/> Website: ' . highlight($term, $row['website']);
    echo '<br/> Info: ' . highlight($term, $row['info']);
    echo '<br/><br/>';
    //echo '<br/> E-Mail:   '.$row['email']; use this for the fields that you dont want to search

}

?>
share|improve this question
add comment

1 Answer

I HIGHLY suggest using PHP PDO with prepared statements ALONG with filtering each field for specific accepted characters.

But to answer your question, your method above is no longer considered safe and can be exploited.

PDO & Tutorial:

You can use preg_match to filter for specific character sequences.

Basic Regex Filter Example:

if (preg_match('/^[0-9-]+$/', $_POST['postcode'])) 
{
    //POSTAL CODE IS GOOD TO GO
    //Filters for charaters "0-9" along with "-" for longer postal codes
}   
else 
{
    //REJECT
}
share|improve this answer
    
If he's using Unicode UTF8, then this code is safe. It's better practise to use PDO however. But there's no need to panic people by saying the code can be exploited, when it cannot. –  soupagain Feb 2 '12 at 13:06
    
@soupagain Interesting.. I've never heard of this UTF8 deal. What makes that secure and how do you force everything to be UTF8? I don't think many people know about that as I've read tons of PHP SQL tutorials/articles/questions without any mention of using specific encoding to make things secure. I could be remembering wrong though. Thanks! –  PiZzL3 Feb 2 '12 at 14:52
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.