douchun3680 2016-08-13 04:43
浏览 56
已采纳

主键ID字段自动增量不允许JSON导入。 PHP / PDO和MySQL

I am trying to import a JSON file using PHP/PDO into a MySQL database. It will import fine if there is no auto incrementing ID field but when I add the field, the JSON file will not import at all.

Table....

enter image description here

Id field set as Primary Key, Auto Increment.

Example JSON data...

{
    "name": "Google", 
    "uri": "https://www.google.com", 
    "description": "The largest and most popular search engine in the world",
}, 
{
    "name": "NFL", 
    "uri": "https://www.nfl.com", 
    "description": "The National Football League",
}, 
{
    "name": "CNN", 
    "uri": "https://www.cnn.com", 
    "description": "Cable News Network",
},

Here is the PHP/PDO code I am using to import the fields...

$jsondata = file_get_contents('http://www.somewebsite/?format=json');
$data = json_decode($jsondata, true);

$stmt = $db->prepare("insert into bookmark values(?,?,?)");

foreach ($data as $row) {
    $stmt->bindParam(1, $row['name']);
    $stmt->bindParam(2, $row['uri']);
    $stmt->bindParam(3, $row['description']);
    $stmt->execute();
}
  • 写回答

1条回答 默认 最新

  • doufen1933 2016-08-13 04:51
    关注

    I believe you should change:

    $stmt = $db->prepare("insert into bookmark values(?,?,?)");
    

    to

    $stmt = $db->prepare("insert (name,uri,description) bookmark values(?,?,?)");
    

    or

    $stmt =  $db->prepare("insert bookmark values(null,?,?,?)");
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站