2

How to pass variable in loop to execute ??? example from one answer here...

$placeholders = array_fill(0, count($array), '?');

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

$stmt = $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();

but what about multiple array. I want add to db 10000 values but not build and bind statement every pass.. Is it possible ? So I want build statement from array, bind params (i don't know how). Than in loop pass variable (identificated by key) and execute...

something universal if I don't wont write statement for every table (just make array of column names and variables)

4

1 回答 1

0

使用准备好的语句和 mysqli 时,您需要做的就是更改存储在绑定参数中的值并再次运行 execute。这是绑定参数的要点,以允许多次执行语句而无需重新发送查询的开销(本质上也是一个很好的安全性,但这是题外话。)

举个例子:

$param1 = '';
$param2 = '';
$param3 = '';
$param4 = '';
$query = 'INSERT INTO table VALUES (?, ?, ?, ?)';
$format = 'ssss';
$params = array(&$param1, &$param2, &$param3, &$param4);
$stmt = $mysqli->stmt_init();
$stmt->prepare($query);
$params = array_merge(array($format), $params); #set up format and parameters for binding
call_user_func_array(array($stmt, 'bind_param'), $params); #parameters specified so bind them


foreach($data as $data_point){
    $param1 = $data_point[0];
    $param2 = $data_point[1];
    $param3 = $data_point[2];
    $param4 = $data_point[3];
    $stmt->execute();
}

这将准备您的语句,然后遍历存储在 $data 中的数据,获取每个值,将其放入准备好的参数中,然后使用新参数执行语句。

里程会因此特定代码而异,因为它不对 sql 错误语句进行任何检查,并且对于许多应用程序在一次插入中执行几行可能会更有效。

于 2012-10-31T18:04:45.940 回答