How to Use a Like Clause in a Pdo Prepared Statement

How do I create a PDO parameterized query with a LIKE statement?

Figured it out right after I posted:

$query = $database->prepare('SELECT * FROM table WHERE column LIKE ?');
$query->execute(array('value%'));

while ($results = $query->fetch())
{
echo $results['column'];
}

implement LIKE query in PDO

You have to include the % signs in the $params, not in the query:

$query = "SELECT * FROM tbl WHERE address LIKE ? OR address LIKE ?";
$params = array("%$var1%", "%$var2%");
$stmt = $handle->prepare($query);
$stmt->execute($params);

If you'd look at the generated query in your previous code, you'd see something like SELECT * FROM tbl WHERE address LIKE '%"foo"%' OR address LIKE '%"bar"%', because the prepared statement is quoting your values inside of an already quoted string.

pdo prepared statements with wildcards

It can work with bind param too in following way:

$name = "%$name%";
$query = $dbh->prepare("SELECT * FROM `gc_users` WHERE `name` like :name");
$query->bindParam(':name', $name);
$query->execute();

Building multi word LIKE Prepared statement for PDO query

I asked the same question on Sitepoint:
https://www.sitepoint.com/community/t/multi-word-like-prepared-statement-for-pdo-query/223738/5

And got a solution there:

$stmt = $pdo->prepare($sql);
if (!empty($sql_str)) {
for ($x = 0; $x<$totalKeywords; $x++) {
// add the percent signs, or make a new copy of the array first if you want to keep the parameters
$keywords[$x] = "%" . $keywords[$x] . "%";
$stmt->bindParam(':search' . $x, $keywords[$x]);
}
}

LIKE query using multiple keywords from search field using PDO prepared statement

Prepared statements protect you from sql injection, so sql code in the parameters will not be interpreted. You will have to build a sql query with the correct number of AND itemTitle LIKE ? before calling prepare().

  $keywords = preg_split('/[\s]+/', $keywords);
$totalKeywords = count($keywords);
$query = "SELECT * FROM prodsTable WHERE itemTitle LIKE ?";

for($i=1 ; $i < $totalKeywords; $i++){
$query .= " AND itemTitle LIKE ? ";
}

$sql=$this->db->prepare($query);
foreach($keywords as $key => $keyword){
$sql->bindValue($key+1, '%'.$keyword.'%');
}
$sql->execute ();


Related Topics



Leave a reply



Submit