带数组的准备语句

2021-12-25 00:00:00 php mysqli

我有一个函数可以做一个简单的插入,但我试图通过传递一个数组来使该方法更加健壮.这是我传递给它的数组:

I have a function to do a simple insert, but am trying to make the method more robust by passing an array. And this is the array I pass into it:

        $form_data = array(
        "sort_order"=>$_POST['sort_order'],
        "name"=>$_POST['page_name'],
        "text"=>$_POST['page_text'],
        "image"=>$_POST['page_image'],
        "meta_desc"=>$_POST['meta_desc'],
        "meta_kw"=>$_POST['meta_kw'],
        "meta_author"=>$_POST['meta_author'],
        "image_thumb"=>"NULL",
    );

这是函数代码:

public function insert_data($array){
        $keys = array();
        $values = array();
        
        foreach($array as $k => $v){
            $keys[] = $k;
            if(!empty($v)){
                $values[] = $v;
            } else {
                $values[] = "NULL";
            }
        }

        $stmt = self::$mysqli->stmt_init();
        $query = "INSERT INTO `".DB_TABLE_PAGES."` (".implode(",",$keys).") VALUES (?,?,?,?,?,?,?,?)";
        
        
        $stmt->prepare($query);
        $stmt->bind_param('ssssssss',implode(",",$values));

        //$stmt->execute();
    }

但我收到此错误:

类型定义字符串中的元素数与绑定变量数不匹配.

Number of elements in type definition string doesn't match number of bind variables.

我知道问题出在哪里,但我不明白如何实现它.

I know what the problem is, but I don't understand how I can achieve it.

推荐答案

试试这个:

public function insert_data($array){
    $placeholders = array_fill(0, count($array), '?');

    $keys = $values = array();
    foreach($array as $k => $v) {
        $keys[] = $k;
        $values[] = !empty($v) ? $v : null;
    }

    $stmt = self::$mysqli->stmt_init();
    $query = 'INSERT INTO `'.DB_TABLE_PAGES.'` '.
             '('.implode(',', $keys).') VALUES '.
             '('.implode(',', $placeholders).')';
    $stmt->prepare($query);

    call_user_func_array(
        array($stmt, 'bind_param'), 
        array_merge(
            array(str_repeat('s', count($values))),
            $values
        )
    );

    $stmt->execute();
}

或者更好的是,改用 PDO:

Or better yet, use PDO instead:

public function insert_data($array){
    $placeholders = array_fill(0, count($array), '?');

    $keys = $values = array();
    foreach($array as $k => $v){
        $keys[] = $k;
        $values[] = !empty($v) ? $v : null;
    }

    // assuming the PDO instance is $pdo
    $query = 'INSERT INTO `'.DB_TABLE_PAGES.'` '.
             '('.implode(',', $keys).') VALUES '.
             '('.implode(',', $placeholders).')';
    $stmt = $pdo->prepare($query);

    $stmt->execute($values);
}

注意:我使用了 null 常量,因为 "NULL" 字符串将被转义为字符串(而不是空值).

Note: I've used the null constant because the "NULL" string will be escaped as a string (not as a null value).

相关文章