0

I have a function that can take any number of parameters like below:

public function executePreparedStatement($query, $paramString = ''){
    $stmt = $this->db->prepare($query);
    if (func_num_args() > 2){
        $parameters = func_get_args();
        array_shift($parameters); // Get rid of the query
        $parameters = array('s', 'email@email.com');  //Hard code for test
        call_user_func_array(array($stmt, "bind_param"), $parameters);
        // $stmt->bind_param($parameters[0], $parameters[1]); //Hard code for test
    }
    $stmt->execute();
    $this->result = $stmt->get_result();
    $stmt->close();
}

The problem is when I run the code as is, The stmt object displays:

No data supplied for parameters in prepared statement

But when I comment out the call_user_func_array call and uncomment the subsequent line, the query works.

ajon
  • 7,868
  • 11
  • 48
  • 86
  • What does `$parameters` contain? – qwertynl Jan 02 '14 at 15:41
  • func_get_args() in my test returns `['SELECT * FROM test WHERE email=?', 's', 'email@email.com']` which I save to $parameters. Then I use array_shift to get rid of the query, so by the time I call bind_param $parameters = ['s', 'email@email.com']; – ajon Jan 02 '14 at 15:45
  • Short answer: it's easier to use PDO when you want to make a generic prepared-statement-execute function like this. – Bill Karwin Jan 02 '14 at 16:16

1 Answers1

2

@Bill_Karwin commented this is a duplicate. I found the solution in that answer. Below is my function (I had to make the values of the parameters be references):

public function executePreparedStatement($query, $paramString = ''){
    $stmt = $this->db->prepare($query);
    if (func_num_args() > 2){
        $parameters = func_get_args();
        array_shift($parameters); // remove the query from the list
        // Array needs to be bound by reference
        foreach ($parameters as $key=>&$value) {
            $parameters[$key] = &$value;
        }
        call_user_func_array(array($stmt, "bind_param"), $parameters);
    }
    $stmt->execute();
    $this->result = $stmt->get_result();
    $stmt->close();
}
ajon
  • 7,868
  • 11
  • 48
  • 86