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
PHP Regex Get Text Between Bbcode Tags
Is There a Difference Between Instantiation with Parentheses or Without
Change Cart Item Prices Based on Custom Cart Item Data in Woocommerce
How to Use Date() in Doctrine 2 Dql
Php: What If I Call a Static Method in Non-Static Way
Interpreting Return Value of Function Directly as an Array
Format 32-Character String with Hyphens to Become Uuid
Send Email by Email Class in Codeigniter with Gmail
Pdo Last Insert Id Always the Right One
Strtolower() for Unicode/Multibyte Strings
Mysql_Fetch_Array Add All Rows
Add a Shipping to an Order Programmatically in Woocommerce 3
How to Ensure I Caught All Errors from MySQLi::Multi_Query
Asynchronous Http Requests in PHP