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

无法在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

图片转代码服务由CSDN问答提供 功能建议

我有一个没有键值对的json格式数据。 当我插入数据我的表时,只插入第一个数据(数组)。 如何将所有数据插入我的数据库表?</ p>

 &lt;?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-&gt; query($ sql); 
} 
 
echo“done ...”; \  n 
?&gt; 
 </ code> </ pre> 
 
 

我的数据库表名是'demo_table',json数据像这样</ p>

  [ “你好世界”, “样品页”, “隐私政策”, “2-修订-V1”, “该横幅标题”] 
上</代码> </ PRE> 
 
  

这是我工作区同一目录中的.txt格式</ p>

我的表模式就像这样</ p>

  CREATE TABLE`  demo_table`(
`id`int(5)NOT NULL,
`data`varchar(255)NOT NULL,
 PRIMARY KEY(`id`)
)ENGINE = InnoDB DEFAULT CHARSET = utf8 
 </ 代码> </ pre> 
 </ div>

1条回答 默认 最新

相关推荐 更多相似问题