我正在编辑一个使用 MySQLi 的脚本。我需要使用准备好的语句将一些值插入到数据库中。
我的数组是这样的形式:
$insert = array('column1' => 'value1', 'column2' => 'value2', 'column3' => 'value3')
到目前为止我已经有了这个,但我需要有关 bind_param
部分的帮助。我在这里看到了使用 call_user_func_array
的文档,但我不确定如何实现它。
$cols = array_keys($insert);
$query = "INSERT IGNORE INTO results (". implode(", ", $cols) .") VALUES (". implode(', ', array_fill(0, count($insert), '?')) .")";
$stmt = $mysqli->prepare($query);
$param = array_merge(array(str_repeat('s', count($insert))), array_values($insert));
call_user_func_array(array($stmt, 'bind_param'), $param);
$stmt->execute();
PHP 5.4.17
不...这绝对比任何数组的 PDO 都难,因为 mysqli_stmt_bind_param()有效...通过将 $array
更改为删除/添加其他列的数据,这可以很好地工作。
$mysqli = new mysqli('localhost', 'root', 'password', 'test');
$array = array("name"=>"pineapple", "color"=>"purple");
$table_name = "fruit";
insert_data($mysqli, $array, $table_name);
function insert_data($mysqli, $array, $table_name)
{
$placeholders = array_fill(0, count($array), '?');
$keys = array();
$values = array();
foreach($array as $k => $v) {
$keys[] = $k;
$values[] = !empty($v) ? $v : null;
}
$query = "insert into $table_name ".
'('.implode(', ', $keys).') values '.
'('.implode(', ', $placeholders).'); ';
// insert into fruit (name, color) values (?, ?);
$stmt = $mysqli->prepare($query);
// create a by reference array...
$params = array();
foreach ($array as &$value) {
$params[] = &$value;
}
$types = array(str_repeat('s', count($params)));
$values = array_merge($types, $params);
/*
$values = Array
(
[0] => ss
[1] => pineapple
[2] => purple
)
*/
call_user_func_array(array($stmt, 'bind_param'), $values);
$success = $stmt->execute();
if ($success) { print "it worked..."; }
else { print "it did not work..."; }
}
我从这些 SO 帖子中得到了一些帮助:
- https://stackoverflow.com/a/15933696/623952
- https://stackoverflow.com/a/6179049/623952
所以...在 $stmt->bind_param()
中,第一个参数是一个字符串,每个传入的参数都有一个字符。该字符表示参数数据类型。在上面的例子中,两个参数都是字符串,所以它变成了ss
。在上面的例子中也总是假设一个字符串。
我在 bind_param()
文档中找到了这个图表:
类型
包含一个或多个字符的字符串,这些字符指定相应绑定(bind)变量的类型:
Type specification chars
Character Description
i corresponding variable has type integer
d corresponding variable has type double
s corresponding variable has type string
b corresponding variable is a blob and will be sent in packets