Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass all parameters as array PHP mysqli query?

Tags:

php

mysql

mysqli

I want to pass all parameters in array rather then pass them one by one .

My Query:

Select col_1,col_2,col_3,col_4 FROM table WHERE col_1=?i AND col_2 =?s AND col_3=?i AND col_4=?s;

$list = $db_con->getAll($sql, 12,'string',18,'name'); //Currently I've passed

Is it possible to pass like following ?

$list = $db_con->getAll($sql, array(12,'string',18,'name')); //Want to do

Thanks in advance.

like image 925
Govind Samrow Avatar asked Aug 19 '26 10:08

Govind Samrow


1 Answers

As of PHP 5.6 you can use a splat operator:

$args = array(12,'string',18,'name');
$list = $db_con->getAll($sql, ...$args); 

If your PHP version is not recent, then call_user_func_array() can be used this way:

$sql = "Select col_1,col_2,col_3,col_4 FROM tabele WHERE col_1=?i AND col_2 =?s AND col_3=?i AND col_4=?s";
$args = array(12,'string',18,'name');
array_unshift($args, $sql);
$list = call_user_func_array(array($db_con, 'getAll'), $args);

but as you can see the first version is way better, not to mention that all PHP versions below 5.6 are already outdated - so I'd strongly encourage you to upgrade instead.

like image 134
Your Common Sense Avatar answered Aug 21 '26 00:08

Your Common Sense



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!