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
?
Within any function, you can use the arguments variable to get an array-like list of all of the arguments passed into the function. You don't need to define it ahead of time. It's a native JavaScript object. You can access specific arguments by calling their index.
Built-in function Like the user-defined functions, we can also pass the built-in function as an argument to another function in Python. Here we will pass the str() function to the map() function along with a Python tuple of strings and numbers. This will return an iterator object which we will to the str.
Assigning the arguments to a regular variable (as in args="$@" ) mashes all the arguments together like "$*" does. If you want to store the arguments in a variable, use an array with args=("$@") (the parentheses make it an array), and then reference them as e.g. "${args[0]}" etc.
While a function can only have one argument of variable length of each type, we can combine both types of functions in one argument. If we do, we must ensure that positional arguments come before named arguments and that fixed arguments come before those of variable length.
How about using:
$args = func_get_args();
call_user_func_array('mysql_safe_query', $args);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With