Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel raw expression is not working when including wildcard parameter

Tags:

php

mysql

laravel

Given the following code:

$sql = "SELECT * FROM items WHERE name LIKE '%?%'";
$key = 'orange';
$result = \DB::select(\DB::raw($sql), [$key]);

the result is always no records!

while by changing LIKE to =, it works fine:

$sql = "SELECT * FROM items WHERE name = ?";

I don't know why this is happening but I have to use RAW in this script. Can anybody figure out where is the problem?

like image 399
William Avatar asked Oct 18 '25 13:10

William


1 Answers

You're failing to understand how bindings work... binding not only handles quotes and other special characters within the value, but also handles the quoting

$sql = "SELECT * FROM items WHERE name LIKE ?";
$key = '%orange%';
$result = \DB::select(\DB::raw($sql), [$key]);

and note the % around the $key value before you bind it

like image 95
Mark Baker Avatar answered Oct 20 '25 03:10

Mark Baker