7

This query is supposed to insert a new user into the 'users' table

$user = DB::getInstance()->insert('users', array(
        'username' => 'jim',
        'password' => 'pass',
        'salt' => 'salt'
       )
);

Corresponding insert()

public function insert($table, $fields = array())
{
    if (count($fields)) {
        $keys   = array_keys($fields);
        $values = null;
        $x      = 1;
        foreach ($fields as $field) {
            $values .= "?";
            if ($x < count($fields)) {
                $values .= ', ';
            }
            $x++;
        }
        $sql = "INSERT INTO users (`" . implode('`,`', $keys) . "`) VALUES ({$values})";
        echo $sql;
        if($this->queryDB($sql,$fields)){
            echo "its good";
            return true;
        }else{
            echo "bad query";
        }
    }
    return false;
}

Attempting to bind query an array of values ($param) as the second parameter of bind_param function

    $stmt = $this->mysqli->prepare($pattern);
    $stmt->bind_param("sss", $param);
    $stmt->execute();

This code keeps returning "mysqli_stmt::bind_param(): Number of elements in type definition string doesn't match number of bind variables" error.

I have also tried call_user_func_array, but keep getting the same error. What ami I doing wrong?

Phil
  • 157,677
  • 23
  • 242
  • 245
qb1234
  • 155
  • 2
  • 14

2 Answers2

12

As of PHP 5.6, you can use the splat operator ...

$stmt->bind_param("sss", ...$param);
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
  • 1
    adding a "..." retirns the following error "Cannot unpack array with string keys". I have also tried call_user func_array with no success. – qb1234 Jun 03 '18 at 20:55
  • 1
    Assuming the fields are in the right order, you can use `array_values($param)` – Nigel Ren Jun 03 '18 at 21:03
2

If you can't get the splat operator to work you may have to update your PHP version to be at least PHP 5.6 in order to pass an array like this:

bind_param("sss", ...$array); 

check your version on linux with:

php --version

I updated mine on Centos 7 to PHP 7.2 and this solved my issue.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Trent
  • 66
  • 4