mpen
mpen

Reputation: 282805

Pass all arguments to another function

I have two functions like this:

function mysql_safe_query($format) {
    $args = array_slice(func_get_args(),1);
    $args = array_map('mysql_safe_string',$args);
    $query = vsprintf($format,$args);
    $result = mysql_query($query);
    if($result === false) echo '<div class="mysql-error">',mysql_error(),'<br/>',$query,'</div>';
    return $result;
}

function mysql_row_exists() {
    $result = mysql_safe_query(func_get_args());
    return mysql_num_rows($result) > 0;
}

The problem is that the second function won't work because it passes the args to the first one as an array, when it expects them as different parameters. Is there any way to get around this, preferably without modifying mysql_safe_query?

Upvotes: 21

Views: 12756

Answers (3)

mpen
mpen

Reputation: 282805

N.B. In PHP 5.6 you can now do this:

function mysql_row_exists(...$args) {
    $result = mysql_safe_query(...$args);
    return mysql_num_rows($result) > 0;
}

Also, for future readers, mysql_* is deprecated -- don't use those functions.

Upvotes: 21

Levite
Levite

Reputation: 17617

Depending on the situation, following might also work for you and might be a little faster.

function  mysql_safe_query($format) {
    $args = func_get_args();
    $args = is_array($args[0]) ? $args[0] : $args; // remove extra container, if needed
    // ...

Which now allows for both types of calling, but might be problematic if your first value is supposed to be an actual array, because it would be unpacked either way.

You could additionally check on the length of your root-array, so it might not be unpacked if if there are other elements, but as mentioned: It is not really that "clean" in general, but might be helpful and fast :-)

Upvotes: 0

John Fiala
John Fiala

Reputation: 4581

How about using:

$args = func_get_args();
call_user_func_array('mysql_safe_query', $args);

Upvotes: 25

Related Questions