不......这绝对比任何数组的 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()
:
types
包含一个或多个字符的字符串,这些字符指定相应绑定变量的类型:
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