1

I have a custom OOP query object with prepared statements that I use for MySQL queries. The problem is that I have a LIKE statement that will not allow me to insert data using a prepared statement.

How can I escape the data in this scenario? Here's my code:

$search_q = !empty($search) ? "AND `title` LIKE '%?%'" : "";
$items = DB::fetch("SELECT `title` FROM `products` WHERE `active` = 1 $search_q;", array($start));
mightyspaj3
  • 471
  • 1
  • 8
  • 22

2 Answers2

4

You need to put the wildcard match characters in the placeholder, not in the query, so instead of doing:

$search = 'find this string';
$db::query("SELECT ... FROM table WHERE col LIKE '%?%' ");

You do:

$search = '%find this string%';
$db::query("SELECT ... FROM table WHERE col LIKE ? ");
Mike
  • 23,542
  • 14
  • 76
  • 87
0

First result in Google serp

$query = $database->prepare('SELECT * FROM table WHERE column LIKE ?');
$query->execute(array('value%'));
while ($results = $query->fetch())
{
    echo $results['column'];
}
Community
  • 1
  • 1
Chris
  • 1,140
  • 15
  • 30