Andurit
Andurit

Reputation: 5762

How to correctly work with array

I have some method which create a MySQL query based on user inputs in form, (it is PHP Nette Framework syntax but its really not important for this question). Correct syntax how I call DB query looks like

$query = "SELECT * FROM candidates WHERE firstname = ? AND surname = ?";
return $this->db->queryArgs($query, ['Dante', 'Hickman']);

But as you can see this is hardcoded so nothing to do with forms. To real form I create another method which collect data and I just call it:

$builder = $this->buildSearchQuery($searchParams);

and after this dump of $builder is array (3)

  0 => "SELECT * FROM candidates WHERE firstname = ? AND surname = ?" (60)
  1 => array (2)
    0 => "Dante" (5)
    1 => "Hickman" (7)
  2 => 2

This data are correct, it's based what I insert to inputs so there are no problem with method buildSearchQuery() But let's describe this array: array[0] is string of query with placeholders base on inputs, array[1][0] and array[1][1] are actualy data (or text) what user fill to inputs. and array[2] is number of inputs filled in.

I'm sure you already noticed that number of inputs can be changed, buildSearchQuery() method for 5 inputs will return something like:

  0 => "SELECT * FROM candidates WHERE firstname = ? AND surname = ? AND favourite = ? AND notFavourite = ? AND random = ?" (60)
  1 => array (5)
    0 => "Dante" (5)
    1 => "Hickman" (7)
    2 => "Pokemon" (7)
    3 => "Digimon" (7)
    4 => "1122334" (7)
  2 => 5

So as you can see, about part "query" part buildSearchQuery() already return correct value, problem is with that values stored in array[1], I'm not sure how I can foreach this to make $query like:

return $this->db->queryArgs($builder[0], [$builder[1][0], $builder[1][1]]);

with dynamic number of array.

Can someone please help me with this? Thanks

Upvotes: 1

Views: 80

Answers (1)

timclutton
timclutton

Reputation: 13004

Since the second element of $builder is already an array you can simply pass it directly as an argument to the function:

return $this->db->queryArgs($builder[0], $builder[1]);

Upvotes: 1

Related Questions