2

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

2
  • 1
    Have you tried implode(",",func_get_args())? Commented Apr 11, 2013 at 19:10
  • 2
    Wouldn't it be much easier if you passed an array to the function instead of multiple scalar arguments? Frankly, variable arguments come to mind much more frequently than it's a good idea to use them. Commented Apr 11, 2013 at 19:12

2 Answers 2

1

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);

Sign up to request clarification or add additional context in comments.

Comments

0

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.