Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

RadicalActivity's avatar

How to Bind parameters to a Raw Query?

Hi,

I have this query:

$this->select('name',
     DB::raw("(
        SELECT  COUNT(id)
        FROM    test 
        WHERE   mid = :member AND created > :from AND created < :to
        ) as numbers", [":member" => $member, ":from" => $from, ":to" => $to])
)
->where('id', '=', '5')
->groupBy('type');

My problem here is that I'm getting an error when I execute this command:

QueryException in Connection.php line 624:
SQLSTATE[HY093]: Invalid parameter number: mixed named and positional parameters

Seems like that how I bind things are incorrent. Can anyone show me what am I missing here?

Cheers!

0 likes
5 replies
petrit's avatar

Do this,

DB::select('select * from test where mid=? and created>? where id=5 group by type', [$member, $from] )

not sure what you are trying to do. Hopefully this will help you

6 likes
RadicalActivity's avatar

Hi petrit,

Thanks for your answer. Actually what I've pasted there is just 10% of the query that I'm using now. So I need my above syntax, can't change that.

Is there any way that I can use named bindings with my above syntax?

Cheers.

ehsanquddusi's avatar

It has to be

$this->select('name',
     DB::raw("(
        SELECT  COUNT(id)
        FROM    test 
        WHERE   mid = :member AND created > :from AND created < :to
        ) as numbers", ["member" => $member, "from" => $from, "to" => $to])
)
->where('id', '=', '5')
->groupBy('type');

Notice the array passed with values. It has to be without :

9 likes
muftisamiullah's avatar

it still shows the error for me

    $Schedule = \DB::select(DB::raw("SELECT * FROM schedule where from_datetime <=:cd AND to_datetime >=:cd AND status = 1 AND id IN (SELECT MAX(id) FROM schedule WHERE is_deleted = 0 AND from_datetime <=:cd AND to_datetime >=:cd AND status = 1 GROUP BY display_serial,type ) ORDER BY id DESC"),['cd'=>$current_date]);
2 likes

Please or to participate in this conversation.