-1

I am using prepared statements for a search functionality using PDO and I am using the like clause. Mysql is 5.5.32

function dblink(){
    # hidden #
    $conn = new PDO("mysql:host=localhost;dbname=$database", 
     $username, $password,  array(
     PDO::ATTR_PERSISTENT => true, 
     PDO::ATTR_EMULATE_PREPARES => false, 
     PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
     PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ
    ));
    return $conn;
}

$conn    = dblink();
$query   = "select * from tablename where attrib like ? ;";
$stmt    = $conn->prepare($query);

$stmt->execute(array($_POST['field']."%"));

$results = $stmt->fetchAll(PDO::FETCH_OBJ);

This dumps all the table contents when user enters % for field in the html form. I thought prepared statement would handle it and there is % in execute so that it matches the substring entered.

How do I use the POST field as normal text only so that it doesn't cause such problem?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Akshay Patil
  • 611
  • 1
  • 10
  • 23
  • 2
    It looks like you can [replace `%` with `[%]`](http://stackoverflow.com/questions/7191449/how-do-i-escape-a-percentage-sign-in-t-sql) but this seems like a hack. – Waleed Khan Jul 15 '13 at 19:08
  • 2
    Maybe the accepted answer to this question might help http://stackoverflow.com/questions/3683746/escaping-mysql-wild-cards – Ma3x Jul 15 '13 at 19:14

1 Answers1

1

This dumps all the table contents when user enters % for field in the html form.

Yes. That's the exact purpose of LIKE operator.
No, it has nothing to do with prepared statement. The latter is used to format your data, not to interfere with query logic.

If you don't like the way your code works - change it. But at the moment it works exactly the way you coded, with no flaws.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345