不...这绝对比任何数组的 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..."; }
}
我从这些帖子中得到了一些帮助:
- 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