Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel query builder doesn't bind values

I am using laravel query builder like this.

$col1 = Input::get('col1','');
$col2 = Input::get('col2','');
$result = DB::table('table1')
        ->select('id', 'col1', 'col2', 'col3')
        ->whereRaw("col1 like '%?%'", [$col1])
        ->whereRaw("col2 like '%?%'", [$col2])
        ->orderBy($orderBy, $orderType) //orderBy=col1, ordeyType=ASC
        ->skip($ofset)->take($limit) //$ofser=0, $limit=10
        ->get(); 

I am getting nothing. If I use toSql() function. I am getting this SQL like this

select `id`, `col1`, `col2`, `col3` 
from `table1` where col1 like '%?%' and col2 like '%?%' 
order by `col1` ASC limit 10 offset 0

The question marks shouldn't be there. It must replace them with the values. I used this code to debug it.

Log::info(var_export(DB::getQueryLog(), true));

The Logs look like this

 2 => 
 array (
'query' => 'select `id`, `col1`, `col2`, `col3` from `table1` where col1 like \'%?%\' and col2 like \'%?%\' order by `col1` ASC limit 10 offset 0',
'bindings' => 
    array (
      0 => 'k',
      1 => '',
   ),
'time' => 25.71,

I think bindings doesn't work pr I'm doing something wrong. Because If I try this code in database It works. (In Addition, I want to get the actual sql that send to the database. How do I do that?)

select `id`, `col1`, `col2`, `col3` from `table1` 
where col1 like '%k%' and col2 like '%%' 
order by `col1` ASC limit 10 offset 0
like image 820
muhammedea Avatar asked Aug 17 '13 09:08

muhammedea


1 Answers

Figured it out. The ? needs to go by itself, so concatenate the % symbols to your col variables. And put your col variables in an array (assuming you're using Laravel 4)

Change:

->whereRaw("col1 like '%?%'", [$col1])
->whereRaw("col2 like '%?%'", [$col2])

To:

->whereRaw("col1 like ?", array('%'.$col1.'%'))
->whereRaw("col2 like ?", array('%'.$col2.'%'))
like image 103
Chris Avatar answered Oct 04 '22 20:10

Chris