ardavar
ardavar

Reputation: 520

Variable input arguments in PHP

I have an half PHP/half algorithmic question. I will have random inputs between 0 and 4. they will be used in the same query such as

  <?php  SELECT * FROM `table` WHERE inputs in (input0,input1,input2)  //for 3 inputs
          SELECT * FROM `table` WHERE inputs in (input0,input1)  //for 2 inputs
         //do nothing for zero inputs ?>

I believe this is the start point.

 <?php
 function myfunc(){
   $args = func_get_args();
  foreach ($args as $arg)
   echo $arg."/n";
 }
  myfunc('hello', 'world', '.');
      ?>

Now I think I can run the foreach loop n times for n individual inputs but I couldn't figure out how to use them in the query effectively. Can I create an array and pass it somehow to the query as inputs?

thanks

arda

Upvotes: 2

Views: 161

Answers (2)

Cano64
Cano64

Reputation: 237

Don't forget to sanitize your inputs first before you use them in a query. Try this

$i = impode(", ", array_map(function($a) {
   return '"' . mysql_real_escape_string($a) . '"';
}, func_get_args());

and then replace (input0,input1) with content of $i like this

$q = "SELECT * FROM `table` WHERE inputs in " . $i;

Upvotes: 0

OdinX
OdinX

Reputation: 4211

You could also pass your function an array:

function myfunc(array('input2','input1'));

But to answer your question using func_get_args:

<?php
function buildQuery() {
    $args = func_get_args();

    $q = implode(', ',$args);

    return 'SELECT * FROM `table` WHERE inputs in ('.$q.');';
}

echo buildQuery('input0','input1');
?>

Outputs:

SELECT * FROM table WHERE inputs in (input0, input1);

Upvotes: 1

Related Questions