PHP – MySQL编写的INSERT数组语句
作者:互联网
我正在编辑一个使用MySQLi的脚本.我需要使用预准备语句将一些值插入到db中.
我的阵列形式为:
$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
解决方法:
不……由于mysqli_stmt_bind_param()的工作方式,这绝对比任何阵列的PDO更难……这可以通过更改$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()中,第一个参数是一个字符串,每个传入的参数都有一个char.而char表示参数数据类型.在上面的示例中,两个参数都是字符串,因此它变为ss.上面的示例中也总是假设一个字符串.
我在bind_param()文档中找到了这个图表:
类型
包含一个或多个字符的字符串,用于指定相应绑定变量的类型:
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
标签:php,mysql,mysqli,sql-insert 来源: https://codeday.me/bug/20191008/1874777.html