Saul_dg
Saul_dg

Reputation: 37

Consult mysql with multidimensional array

im trying all what came to my mind but nothing works.

i have an array like this

$sku _list = Array(
[0] => Array
    (
        [sku] => 885370773958
    )

[1] => Array
    (
        [sku] => 711719805205
    ))

With the next code to make consult

$db =  new mysqli("localhost", "user", "pass", "db");   
$consult_sku = $db->query("SELECT * FROM fullfilment WHERE sku IN (" . implode(",", array_map(function ($sku_entry) { return $sku_entry['sku'];},$sku_list)) . ")"); 

getting the next array, only with the first value of the $sku_list

    Array
(
    [0] => 885370773958
    [sku] => 885370773958
    [1] => CAMO
    [name] => CAMO
    [2] => 1
    [quantity] => 1
)

i want to recover an array similar to $sku_list to compare, wich way is the best to get the result?

Greetings!

Upvotes: 0

Views: 49

Answers (1)

KIKO Software
KIKO Software

Reputation: 16761

There's no shame in using PHP code, and it will execute quite fast. So instead of putting this monster in you query:

array_map(function ($sku_entry) { return $sku_entry['sku'];},$sku_list)

you could write simple to understand PHP code like this in front of your query:

foreach ($sku_list as $item) $sku[] = $item['sku'];

Then do the query:

$sql = 'SELECT sku FROM fullfilment WHERE sku IN ('.implode(',',$sku).')';
$result_sku = $db->query($sql);

Don't be afraid of multiple lines, it makes your code easier to read and understand. After this you can extract information from your results:

while($row = $result_sku->fetch_assoc()) {
  $sku_found[] = $row;
}

Now $sku_found will be similary structured to $sku_list.

Note that your SQL command contained a * which means you retrieve all columns. In my example only used the sku column.

Upvotes: 1

Related Questions