2

What is the best way to pass a variable number of arguments to a php function? I mean, suppose i have the following:

function my_func($a, $b, $c) {
    $q = 'SELECT ' . $a . ' FROM ' . $b . ' WHERE status IS NULL';
}

my_func('id', 'table');
my_func('id', 'table', ' AND x = 1');

I've read about func_get_arg(), but if i call func_get_arg(2) in the first situation, i will get a, Argument 2 not passed to function error.

IMPORTANT: this query is not performed with user-passed arguments, so no injection hazzards! It is performed with controlled arguments given by me and its function is to check if that value is valid within a combination of foreign keys! So please no sarcastic 'injection paradise' comments, thank you.

7
  • 8
    Please don't form SQL using string concatenation. Please use parameterised or prepared queries instead. Commented Mar 29, 2014 at 9:31
  • 1
    you can set a array as variable, there you can set as many as you wish Commented Mar 29, 2014 at 9:32
  • 3
    SQL injection paradise Commented Mar 29, 2014 at 9:32
  • 1
    Set your defaults for the params such as my_func($a, $b, $c=false) in your case and within the function if($c) use $c. Commented Mar 29, 2014 at 9:51
  • @Dai i've updated the question to better explain the scenario... Commented Mar 29, 2014 at 9:52

2 Answers 2

2

Well i do not know if it's best, but i like to pass the array as argument and then work with it in my function. Here is one example:

function my_query($query = array())
{
    // select and from are required to exist
    if(!empty($query) && array_key_exists('select', $query) && array_key_exists('from', $query))
    {
        $q  = "select {$query['select']}";
        $q .= " from {$query['from']}";

        foreach($query as $key => $val)
        {
            // Don't want to include select and from once again (also do not unset before in case need to run all of this once again)
            if($key != 'select' && $key != 'from')
            {
                // Search if key has underscore and replace it with space for valid query
                if(strpos($key, '_') !== false)
                    $key = str_replace('_', ' ', $key);

                // Build query with spaces and all
                $q .= " " . $key . " " . $val;
            }
        }

        // Run query here using $q
    }
}

And you can pass in array as you like:

$query = array(
    'select'    => '*',
    'from'      => 'users',
    'where'     => 'age > 25',
    'order by'  => 'id'
);

// Or 
$query = array();

$query['select']    = '*';
$query['from']  = 'users';
$query['where'] = 'age > 25';
$query['order_by']  = 'id';

my_query($query);

// Would return us something like this
string(46) "select * from users where age > 25 order by id"

But using this you have to maintain right order in your array or write ordering and validation code in your function.

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

Comments

1

Since you have mentioned that your function does not deal with user-passed arguments.. I am suggesting this..

FYI : I just used an echo inside that for demonstration purposes.. you can change that later.

<?php
function my_func() {

    echo $q = 'SELECT ' . func_get_arg(0) . ' FROM ' . func_get_arg(1) . ' WHERE status IS NULL';
}

my_func('id', 'table');

The above displays...

SELECT id FROM table WHERE status IS NULL

The arguments start from 0 index, so you should probably do.. func_get_arg(1) to get the second argument.

4 Comments

Hi Shankar, maybe i wasn't clear but this was my first try (you can read it in my question just after the code). Problem is that there could be 2 or more possible arguments passed and so if i use func_get_arg(2) i will get a php error...
Why not use func_get_args() that returns all the arguments in an array and you use func_num_args to know how many arguments passed and you can write your script accordingly... right ?
ok...makes sense...but isn't easier to pass an array at this point?
When all those arguments passed are there inside the array , you can very well easily find out the length(total args) and there won't be any chance for argument mismatch error.

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.