mpen
mpen

Reputation: 282895

call_user_func_array with references

I'm basically trying to call mysqli::bind_param via call_user_func_array.

Here's my function:

function Insert($table, $values=array(), $flags=0) {
    $field_count = count($values);
    
    if($field_count > 0) {
        $fields = implode(',',array_keys($values));
        $placeholders = implode(',',array_repeat('?',$field_count));
    } else {
        $fields = '';
        $placeholders = '';
    }

    if($flags > 0) {
        $flag_arr = array();
        if($flags & self::LOW_PRIORITY) $flag_arr[] = 'LOW_PRIORITY';
        if($flags & self::DELAYED) $flag_arr[] = 'DELAYED';
        if($flags & self::HIGH_PRIORITY) $flag_arr[] = 'HIGH_PRIORITY';
        if($flags & self::IGNORE) $flag_arr[] = 'IGNORE';
        $flags_str = implode(' ',$flag_arr);
    } else {
        $flags_str = '';
    }
    
    $sql = "INSERT $flags_str INTO $table ($fields) VALUES ($placeholders)";
    $stmt = $this->mysqli->prepare($sql);
    if($stmt === false) {
        throw new Exception('Error preparing MySQL statement.<br/>MSG: '.$this->mysqli->error.'<br/>SQL: '.$sql);
    }
    
    if($field_count > 0) {
        $types = '';
        foreach($values as $val) {
            if(is_int($val)) $types .= 'i';
            elseif(is_float($val)) $types .= 'd';
            elseif(is_string($val)) $types .= 's';
            else $types .= 'b';
        }
        $params = array_merge(array($types),array_values($values));
        call_user_func_array(array($stmt,'bind_param'),$params);
    }
    
    $stmt->execute();
    return $stmt;
}

The problem occurs on the call_user_func_array line. I get this error:

Parameter 2 to mysqli_stmt::bind_param() expected to be a reference, value given

I understand the problem, I'm just not sure how to work around it.

As an example, the function may be called like this:

$db->Insert('pictures',array('views'=>1));

And var_dump($params) would yield this:

array
  0 => string 'i' (length=1)
  1 => int 1

So, is there a way to call mysqli::bind_param with a variable number of arguments, or somehow make my array into references?

Upvotes: 1

Views: 1935

Answers (1)

simshaun
simshaun

Reputation: 21466

The second note in the manual page for mysqli_stmt::bind_param() states:

Care must be taken when using mysqli_stmt_bind_param() in conjunction with call_user_func_array(). Note that mysqli_stmt_bind_param() requires parameters to be passed by reference, whereas call_user_func_array() can accept as a parameter a list of variables that can represent references or values.

There is a solution posted in the user-comments section in the manual. In short, you make a function that accepts an array and returns a duplicate array whose elements are references to the elements in the source array.

Edit: Turns out there are a couple SO questions on this.

Upvotes: 5

Related Questions