带数组的准备语句 [英] Prepared statements with an array

查看:34
本文介绍了带数组的准备语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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).

这篇关于带数组的准备语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆