3

What do you guys do when you don't know the number of parameters that you are going to receive?

for example:

if($a==1) $filter.=" AND u.name = ?";
if($b==1) $filter.=" AND u.address = ?";
if($c==1) $filter.=" AND u.age = ?";
if($d==1) $filter.=" AND u.city = ?";
ETC...

$stmt->prepare("SELECT id
                FROM users u
                WHERE u.cp = ?
                ".$filter);

$stmt->bind_param("i", $cp);

And now? if you are receiving $a = 1 you will get an error because you are only passing 1 parameter on the bind_param. So you don't know if you are going to receive 1, 2, 3 or 4 params and I don't want to make a lot of IF or I must use a loop to count the number of parameters?

ata
  • 3,398
  • 5
  • 20
  • 31

1 Answers1

2

You'll have to manage the list of arguments (type and value) as you add the conditions. This means you need to use call_user_func_array to pass the list of values to bind_param.

Basically, in each of your if statements, not only add the condition, but also add the parameter type (e.g. $types .= 'i') and the parameter (e.g. $args[]=$arg).

You'll find a good example on how to do this in this comment of the bind_param documentation: http://www.php.net/manual/en/mysqli-stmt.bind-param.php#109256

jcaron
  • 17,302
  • 6
  • 32
  • 46