Binding parameter to Db::raw laravel query

B Faley picture B Faley · Jan 28, 2017 · Viewed 13.8k times · Source

I've got the following raw query:

$results = Db::select( Db::raw("SELECT HOUR(created_at) as hour, COUNT(*) as count
                       FROM `visited`
                       WHERE created_at >= DATE_SUB(NOW(),INTERVAL 16 DAY)
                       GROUP BY HOUR(created_at)") );

I need to parameterize the day interval, so I tried this:

$days = 16;
$results = Db::select( Db::raw("SELECT HOUR(created_at) as hour, COUNT(*) as count
                       FROM `visited`
                       WHERE created_at >= DATE_SUB(NOW(),INTERVAL :days DAY)
                       GROUP BY HOUR(created_at)", ["days" => $days]) );

But I am getting the following error:

"SQLSTATE[HY000]: General error: 2031

Apparently the binding is not working. What am I doing wrong?

Answer

Artenes Nogueira picture Artenes Nogueira · Jan 28, 2017

Try this:

$results = DB::select('SELECT HOUR(created_at) as hour, COUNT(*) as count FROM visited WHERE created_at >= DATE_SUB(NOW(),INTERVAL ? DAY) GROUP BY HOUR(created_at)', [16]);

You can even use named bindings:

$results = DB::select('SELECT HOUR(created_at) as hour, COUNT(*) as count FROM visited WHERE created_at >= DATE_SUB(NOW(),INTERVAL :days DAY) GROUP BY HOUR(created_at)', ['days' => 16]);

Don't need to use DB::raw(), just use DB::select() for simple raw select queries: https://laravel.com/docs/master/database#running-queries