2

I have a PHP search suggestion script which uses MySQL as its back-end. I am aware there are many vunerabilities in my code, I was just wondering what I can do to make it more secure.

Here is my code:

<?php
$database=new mysqli('localhost','username','password','database');
if(isset($_POST['query'])){
    $query=$database->real_escape_string($_POST['query']);
    if(strlen($query)>0){
        $suggestions=$database->query(
            "SELECT * FROM search WHERE name LIKE '%" . $query .
             "%' ORDER BY value DESC LIMIT 5");
        if($suggestions){
            while($result=$suggestions->fetch_object()){
                 echo '<a>'.$result->name.'</a>';                       
            }
        }
    }
}
?>
1
  • In what sense do you want to make it more secure? Since you are already escaping the search string, what is it you are looking to secure? Commented Jun 1, 2011 at 23:41

2 Answers 2

4

Actually there aren't, considering you are escaping the only external value in the SQL

Anyway I suggest you to use PDO::prepare for queries. Go here for further infos

http://it.php.net/manual/en/pdo.prepare.php

Example:

$sth = $dbh->prepare('SELECT * FROM article WHERE id = ?');
$sth->execute(array(1));
$red = $sth->fetchAll();
Sign up to request clarification or add additional context in comments.

Comments

3

Some tips from me:

  • use PDO,
  • don't concatenate query parameters, use prepared statements in PDO,
  • don't put "*" in SELECT statement, get only the columns you'll need,
  • use fetchAll() in PDO, don't fetch records in while() loop.

1 Comment

I am not the downvoter But I could try to explain why they downvoted: the OP asked not tips but if there were vulernatibiles. he didn't asked for PDO fetchAll neither for SQL optimization with SELECT *. Maybe it's for that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.