duanchen7401 2019-03-31 08:35
浏览 130
已采纳

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

I have a json format data without key value pair. 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

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

which is a .txt format in the same directory of my workspace

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
  • 写回答

1条回答 默认 最新

  • doupinge9055 2019-03-31 09:02
    关注

    Seems you have not a proper primary key.

    Try create in the demo_table a proper primary key based on auto increment column

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 对于这个问题的代码运行
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败