Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

implement LIKE query in PDO

I am running problems in implementing LIKE in PDO

I have this query:

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

I checked the $var1 and $var2 they contain both the words I want to search, my PDO is working fine since some of my queries SELECT INSERT they work, it's just that I am not familiar in LIKE here in PDO.

The result is none returned. Do my $query is syntactically correct?

like image 968
Leandro Garcia Avatar asked Jun 20 '12 10:06

Leandro Garcia


4 Answers

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.

like image 189
Carlos Campderrós Avatar answered Nov 14 '22 20:11

Carlos Campderrós


Simply use the following:

$query = "SELECT * FROM tbl WHERE address LIKE CONCAT('%', :var1, '%')
            OR address LIKE CONCAT('%', :var2, '%')";

$ar_val = array(':var1'=>$var1, ':var2'=>$var2);
if($sqlprep->execute($ar_val)) { ... }
like image 24
Grant Avatar answered Nov 14 '22 22:11

Grant


No, you don't need to quote prepare placeholders. Also, include the % marks inside of your variables.

LIKE ?

And in the variable: %string%

like image 6
Madara's Ghost Avatar answered Nov 14 '22 20:11

Madara's Ghost


$query = "SELECT * FROM tbl WHERE address LIKE ? OR address LIKE ?";
$params = array("%$var1%", "%$var2%");
$stmt = $handle->prepare($query);
$stmt->execute($params);
like image 4
Miqdad Ali Avatar answered Nov 14 '22 21:11

Miqdad Ali