mysql 数组 插入,使用mysqli从数组插入MySQL

I want to insert some data from a parsed JSON to a table, but when I do it, it doesn't work, it returns 0 rows, what am I missing? I'm new yet with this "mysqli". I have more than 25000 rows to insert to the table.

$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);

}

解决方案

Seems like you should set single quotes around your data values. Also adding a mysqli_error check for your mysqli_query line so you can actually see what is happening:

$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));

}

Or better yet, use mysqli_stmt_bind_param like this. Allow MySQLi to deal with the whole query data structuring instead of having to worry about single quote placement. Also, added a check for mysqli_connect_error on your mysqli_connect line:

// 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));

}

Note that I have a commented line for the mysqli_stmt_bind_param since it’s not clear to me if your $value['data_id'] is a number or a string. The mysqli_stmt_bind_param($query, 'is',… means the first value is an integer (i) and the next value is a string (s). Feel free to adjust to best fit your actual data types.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值