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

用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 :)

  • 写回答

4条回答 默认 最新

  • doubi12138 2016-10-02 15:39
    关注
    • To iterate over array you have to use foreach operator.
    • To perform multiple inserts you have to use prepared statements

    So despite what in all other hastily written answers said, the code should be

    $stmt = $con->prepare("INSERT INTO `table` (`id`, `name`, `status`) VALUES (?,?,?)");
    $stmt->bind_param("sss", $id, $name, $status);
    foreach ($data as $row)
    {
        $id = $row['id'];
        $name = $row['name'];
        $status = $row['status'];
        $stmt->execute();
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多
  • ¥50 求一个win系统下运行的可自动抓取arm64架构deb安装包和其依赖包的软件。
  • ¥60 fail to initialize keyboard hotkeys through kernel.0000000000