dousikuai5417
2016-10-02 15:14
采纳率: 0%
浏览 197
已采纳

用PHP将数组插入MySQL数据库?

Here's my current code:

// connect to database  
$con = mysqli_connect("localhost","username","password","database");
if (!$con) {
    die('Could not connect: ' . mysqli_error());
}

// get the json file
$jsondata = file_get_contents('http://www.example.com');

// convert json to php array
$data = json_decode($jsondata, true);

// assign each of the variables
$id = $data['0']['id'];
$name = $data['0']['name'];
$status = $data['0']['status'];

$insertstatement = mysqli_query($con,"INSERT INTO `table` (`id`, `name`, `status`) VALUES ('".$id."', '".$name."', '".$status."');");

Technically this code is working, but it's only adding the first item.

For example, here's the original json that's being imported:

[
   {
      "id":"19839",
      "status":"active",
      "name":"First Name",
   },
   {
      "id":"19840",
      "status":"active",
      "name":"Second Name",
   },
   {
      "id":"19841",
      "status":"active",
      "name":"Another Name",
   },
   {
      "id":"19842",
      "status":"active",
      "name":"Last Name",
   }
]

My code would only be inserting this into the database:

{
 "id":"19839",
 "status":"active",
 "name":"First Name",
}

How do I make it loop through all of them and insert all of the rows? Also is there, a way to insert them in reverse order (starting from the last one, ending at the first one)?

Any help would be greatly appreciated :)

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

这是我当前的代码:

  //连接数据库 
 $ con = mysqli_connect(“localhost”,“username”,“password”,“database”); 
if(!$ con){
 die('无法连接:'。mysqli_error()); 
  } 
 
 //获取json文件
 $ jsondata = file_get_contents('http://www.example.com'); 
 
 //将json转换为php数组
 $ data = json_decode($  jsondata,true); 
 
 //分配每个变量
 $ id = $ data ['0'] ['id']; 
 $ name = $ data ['0'] ['name'  ]; 
 $ status = $ data ['0'] ['status']; 
 
 $ insertstatement = mysqli_query($ con,“INSERT INTO`table`(`id`,`name`,`status`  )VALUES('“。$ id。”','“。$ name。”','“。$ status。”');“); 
   
 
 

从技术上讲,这段代码正在运行,但它只是添加了第一项。

例如,这里是导入的原始json:

  [
 {
“id”:“19839”,
“status”:“active”,
“name”:“First Name”,
},
 {
“id”:“  19840“,
”status“:”active“,
”na  me“:”Second Name“,
},
 {
”id“:”19841“,
”status“:”active“,
”name“:”Another Name“,
},  
 {
“id”:“19842”,
“status”:“active”,
“name”:“姓氏”,
} 
] 
    
 
 

我的代码只会将其插入数据库:

  {
“id”:“19839”,
“status”:“  active“,
”name“:”First Name“,
} 
   
 
 

如何让它循环遍历所有行并插入所有行 ? 还有,一种方法以相反的顺序插入它们(从最后一个开始,到第一个结束)?

任何帮助将不胜感激:) \ n

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

4条回答 默认 最新

相关推荐 更多相似问题