嗨我想从解析的json中将一些数据插入到表中,但是当我这样做时,它不起作用,它返回0行,我缺少什么?我已经使用了这个" mysqli" ..我有超过25000行要插入到表中。 THX
$mysqli = mysqli_connect('localhost', 'root', '', '');
$allData = $dataSource->getAllData();
foreach ($allData as $key => $value) {
$query = 'INSERT INTO `table`(`data_id`, `name`) VALUES (' . $value['data_id'] . ', ' . $value['name'] . ')';
$result = mysqli_query($mysqli, $query);
}
它现在有效,它插入了所有对象数据,我回复的代码是这样的:
$mysqli = mysqli_connect('localhost', 'root', '', '') or die(mysqli_connect_error());
if (!$mysqli) {
die('Could not connect: ' . mysqli_error());
}
$ allData = $ dataSource-> getAllData();
foreach ($allData as $key => $value) {
$query = mysqli_prepare($mysqli, "INSERT INTO `table`(`data_id`, `name`) VALUES (?, ?)");
mysqli_stmt_bind_param($query, 'is', $value['data_id'], $value['name']);
mysqli_stmt_execute($query);
mysqli_stmt_close($query);
}
希望一切顺利,我是这个mysqli的新手,我需要大量的编程练习
答案 0 :(得分:1)
好像你应该在数据值周围设置单引号。同时为mysqli_error
行添加mysqli_query
支票,以便您可以真正了解所发生的情况:
$allData = $dataSource->getAllData();
foreach ($allData as $key => $value) {
$query = "INSERT INTO `table`(`data_id`, `name`) VALUES ('" . $value['data_id'] . "', '" . $value['name'] . "')";
$result = mysqli_query($mysqli, $query) or die(mysqli_error());
}
或者更好的是,像这样使用mysqli_stmt_bind_param
。允许MySQLi处理整个查询数据结构,而不必担心单引号放置。另外,在mysqli_connect_error
行添加了对mysqli_connect
的检查:
// Connecting, selecting database
$mysqli = mysqli_connect('localhost', 'root', '', '') or die(mysqli_connect_error());
$allData = $dataSource->getAllData();
foreach ($allData as $key => $value) {
// Set the query.
$query = "INSERT INTO `table`(`data_id`, `name`) VALUES (?, ?)";
// Bind the params.
// mysqli_stmt_bind_param($query, 'ss', $value['data_id'], $value['name']);
mysqli_stmt_bind_param($query, 'is', $value['data_id'], $value['name']);
// Run the query.
$result = mysqli_query($mysqli, $query) or die(mysqli_error());
}
请注意,我有mysqli_stmt_bind_param
的注释行,因为我不清楚$value['data_id']
是数字还是字符串。 mysqli_stmt_bind_param($query, 'is',…
表示第一个值是整数(i
),下一个值是字符串(s
)。您可以随意调整以适合您的实际数据类型。
答案 1 :(得分:-1)
更自动的解决方案是:
$link = mysqli_connect('localhost', 'root', 'password', 'mydatabase') or die(mysqli_connect_error());
foreach ($groups as $key => $values) {
$valuesArray = array();
// figure out if we have to encapsulate in ''
foreach($values as $key => $value){
switch(gettype($value)){
case 'boolean':
case 'integer':
case 'double': // includes float
$valuesArray[] = $value;
break;
case 'string':
$valuesArray[] = '\''.$value.'\'';
break;
default:
die('not possible');
break;
}
}
$query = 'INSERT INTO mydatabase.mytable(' . implode(',',array_keys($values)) . ') VALUES (' . implode(',',$valuesArray) . ')';
// echo $query; // debug
$result = mysqli_query($link, $query) or die(mysqli_error());
}
这个解决方案再次是明确的mysqli,外部输入使用预处理语句或pdo等!