Search code examples
phppdoinsert

Invalid parameter number: number of bound variables does not match number of tokens PDO insert


function mysql_insert($data_array){
    $sql = "insert into `". $this->table_name. '`';

    $array_keys = array_keys($data_array);
    $array_keys_comma = implode(",\n", preg_replace('/^(.*?)$/', "`$1`", $array_keys));

    for($a=0,$b=count($data_array); $a<$b; $a++){ $question_marks .="?,";  }

    $array_values = array_values($data_array);
    $array_values_comma = implode(",", $array_values);

    $sql.= " ($array_keys_comma) ";
    $sql.= " values(". substr($question_marks, 0,-1) .")";

    $prepare = $this->connDB->prepare($sql);
    $insert = $prepare->execute(array($array_values_comma));

}

I want to creat like this universal functions, $data_array-comes from $_POST This function will work for all form. But i dont know what is my wrong :S


Solution

  • $array_values_comma is a scalar after you implode() the array. So you always pass an array of one element to your execute() function. You should pass $array_values.

    Here's how I'd write this function:

    function mysql_insert($data_array){
        $columns = array_keys($data_array);
        $column_list_delimited = implode(",", 
          array_map(function ($name) { return "`$name`"; }, $columns));
    
        $question_marks = implode(",", array_fill(1, count($data_array), "?"));
    
        $sql = "insert into `{$this->table_name}` ($column_list_delimited) 
          values ($question_marks)";
    
        // always check for these functions returning FALSE, which indicates an error
        // or alternatively set the PDO attribute to use exceptions
    
        $prepare = $this->connDB->prepare($sql);
        if ($prepare === false) {
          trigger_error(print_r($this->connDB->errorInfo(),true), E_USER_ERROR);
        }
    
        $insert = $prepare->execute(array_values($data_array));    
        if ($insert === false) {
          trigger_error(print_r($prepare->errorInfo(),true), E_USER_ERROR);
        }
    
    }
    

    A further improvement would be to do some validation of $this->table_name and the keys of $data_array so you know they match an existing table and its columns.

    See my answer to escaping column name with PDO for an example of validating column names.