简体   繁体   English

无法将json数据插入php中的mysql数据库

[英]can't insert json data into mysql database in php

I have a json format data without key value pair. 我有一个没有键值对的json格式数据。 when i insert data my table only the 1st data is inserted(of the array). 当我在表中插入数据时,仅插入(数组的)第一数据。 how i insert the all data into my databse table? 我如何将所有数据插入我的数据库表?

<?php

$mysqli = new mysqli('localhost','root','','user');
$my_json_data = file_get_contents('./jason_data.txt');
$my_data = json_decode($my_json_data,true);


foreach($my_data as $data){

    $sql = "INSERT INTO demo_table (data) VALUES ('$data');";
    $mysqli->query($sql);
}

echo "done...";

?>

my database table name is 'demo_table' and json data fromat like this 我的数据库表名称是'demo_table'和这样的json数据

["hello-world","sample-page","privacy-policy","2-revision-v1","the-banner-title"]

which is a .txt format in the same directory of my workspace 这是我工作区同一目录中的.txt格式

my table schema is like this 我的表架构是这样的

CREATE TABLE `demo_table` (
 `id` int(5) NOT NULL,
 `data` varchar(255) NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

Seems you have not a proper primary key. 似乎您没有正确的主键。

Try create in the demo_table a proper primary key based on auto increment column 尝试在demo_table中基于自动增量列创建正确的主键

based on your schema add autoincrement 根据您的架构添加自动增量

CREATE TABLE `demo_table` (
  `id` int(5) NOT NULL  AUTO_INCREMENT,
  `data` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

in this each row inserted have a automatic different primary key .. otherwise the first insertion create an id = 0 and the second try to do the same ..but 0 already exist 在此插入的每一行都有一个自动的不同主键..否则,第一次插入创建一个id = 0,第二次尝试执行相同的操作..但已经存在0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM