尝试将$ json数组值放入数据库但遗憾的是由于某些原因它不起作用,我找不到原因。我的第一个猜测是因为它可能是mysql中的varchar255?
<?php
$json = '[
{
"order_id":123,
"kases_id":12,
"product_quantity":121,
"product_name":"suns",
"postage_adress":"garaazha",
"barcode":"2131231"
}
]';
//create a DB connection
$connect = mysqli_connect("localhost", "root", "", "qrbuddy");
$result = json_decode($json);
foreach($result as $key => $value) {
if($value) {
mysqli_query($connect, "INSERT INTO qrbuddy (order_id, kases_id, product_quantity, product_name, postage_adress, barcode, status) VALUES ($value->order_id, $value->kases_id,$value->product_quantity,$value->product_name,$value->postage_adress,$value->barcode, 0)");
}
mysqli_close($connect);
}
?>
我的数据库:
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
CREATE TABLE `qrbuddy` (
`order_id` int(11) NOT NULL,
`kases_id` int(11) NOT NULL,
`product_quantity` int(11) NOT NULL,
`product_name` varchar(255) NOT NULL,
`postage_adress` varchar(255) NOT NULL,
`barcode` varchar(255) NOT NULL,
`status` tinyint(1) NOT NULL DEFAULT '0'
)
答案 0 :(得分:0)
试试这样:
$result = json_decode($json);
foreach($result as $key => $value) {
if($value) {
mysqli_query($connect, "INSERT INTO `your_DATABASE_NAME`.`qrbuddy` (`order_id`, `kases_id`, `product_quantity`, `product_name`, `postage_adress`, `barcode`, `status`) VALUES ({$value->order_id}, {$value->kases_id},{$value->product_quantity},{$value->product_name},{$value->postage_adress},{$value->barcode}, 0)");
}
mysqli_close($connect);
}
最近我注意到我还需要指定数据库名称,以便查询100%正常工作。
编辑:忘记指定,确保编写数据库名称而不是 your_DATABASE_NAME
。只是确保你不会在这个上浪费太多时间:)
另外,根据我自己的经验,在大括号 {$ variable} 中编写变量,会给出更高的%,查询将起作用。 (无论如何它更容易阅读=)