-2

I need help creating a function in PHP that accepts optional variables. So far this is what I have done:

function customFunc($var, $var1){
    global $conn;
    $query = "SELECT * FROM table WHERE col = '{$var}' AND col1 = '{$var1}';";
    $result = mysqli_query($conn, $query);
    return $result;
}

If I call the function without supplying $var1, MySQL does not return any rows, even though we have some.

Now what I also need to do is select all from col1 if $var1 is not set. I would also like to scale up the function and include more optional variables $var2, $var3, etc like so:

function customFunc($var, $var1, $var2, $var3){
    global $conn;
    $query = "SELECT * FROM table WHERE col = '{$var}' AND col1 = '{$var1}' AND col2 = '{$var2}' AND col3 = $var3;";
    $result = mysqli_query($conn, $query);
    return $result;
}
Kirk Beard
  • 9,569
  • 12
  • 43
  • 47
Kha Kali
  • 169
  • 2
  • 13

3 Answers3

0

You can have optional parameters by declaring a default value for the parameter like so:

function abc($a, $b, $c = '') { ... }

You should pass the optional parameter at the last possible position, if possible. Thats to ensure non breaking code when altering a function later on.

paskl
  • 589
  • 4
  • 25
  • This is a bad example. Arguments without default values should come before arguments with default values. Your example should be: function abc($b, $a= '', $c = '') { ... } – jakub_jo Feb 20 '16 at 21:20
  • You are right. I will update the answer. – paskl Feb 20 '16 at 21:22
0

You need to assign default values for your arguments:

function customFunc($var = null, $var1 = null) {
}

Than you've to check for existence of these default values and modify your query accordingly.

Or you could use, as suggested in comments, func_get_args() and map these dynamic arguments to columns like this:

function customFunc() {
    $map = [
        'col1', 'col2', 'col3'
    ];

    $where = [];
    $i = 0;
    foreach (func_get_args() as $arg) {
        if (!isset($map[$i])) {
            break;
        }
        $where[]= $map[$i] . '=\'' . $arg . '\'';
        $i++;
    }

    if (empty($where)) {
        return null;
    }

    $query = 'SELECT * FROM table WHERE ' . implode(' AND ', $where) . ';';
    $result = mysqli_query($conn, $query);
    return $result;
}
jakub_jo
  • 1,494
  • 17
  • 22
0

Try this:

function customFunc($var1=null, $var2=null, $var3=null) {
$query = "SELECT * FROM Table;
if ($var1) {
    $query .= " WHERE col1 ='$var1'";
}
 if ($var2) {
    $query .= " AND col2='$var2'";
}
 if ($var3) {
    $query .= " AND col3='$var3'";
}
return mysql_query($query);

}

Diego Vidal
  • 1,022
  • 12
  • 21