0

I upgraded an script from MySQL to MySQLi extension in PHP. The code looks like:

array_map('mysqli_query', $sqls);

And, I met an error there which was working on the past.

Warning: mysqli_query() expects at least 2 parameters, 1 given in file.php on line __

The $sqls is an array of valid SQL strings. mysqli_ needs $connection to be supplied. But is it possible to run still with the same array_map?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Bimal Poudel
  • 1,214
  • 2
  • 18
  • 41

1 Answers1

0

Yes you can. array_map can be passed multiple parameters, each of which is an array with the values you need to pass to the callback function. So in this case you need an array of connections and an array of sqls.

You can use array_fill to make an array with copies of the same connection (for objects, only the reference is copied, so you won't have multiple actual connections to the database).

Then, this should work:

<?php

$connections = array_fill(0, count($sqls), $connection);

array_map('mysqli_query', $connections, $sqls);

To make it a bit more understandable, I'd wrap this in a function.

function mysqli_query_multiple($connection, $sqls)
{
    $connections = array_fill(0, count($sqls), $connection);
    array_map('mysqli_query', $connections, $sqls);
}

Or maybe it's just as easy and readable to use a for loop.

GolezTrol
  • 114,394
  • 18
  • 182
  • 210