dpi9530 2014-11-12 17:01
浏览 592

如何将Json插入mysql数据库?

Hi I'm trying to insert the json array into my MySQL database. but I have a problem if I insert my Json data and try to insert into my database, display in browser is empty. I dont know how to fix it, please tell me and help me for this.

Here its my json data

[{"id_peneliti":1083,"id_prodi":"4","nama_lengkap":"hasil edit","nama_tampilan":"duplikat","nip":"11111111222222222222","foto_user":"img\/foto\/2b8a1f40237e7f58bf0f7376fc8d5288.jpeg","email":"email@gmail.com","phone":"+39ry982835982","riwayat_pendidikan":"
sfbvxlkmblfkblkn<\/p>
"}]

here is my parsing json

<?
 $json_url = "http://localhost/location/create_jsoninput.php";
 $json = file_get_contents($json_url);
 $data = json_decode($json,true);

 //Database Connection
mysql_connect("localhost","name","pass") or die(mysql_error());
mysql_select_db("db_name") or die(mysql_error());

    if (foreach ($data as $item)) {
       mysql_query("INSERT INTO tb_database VALUES ('".$item['id_peneliti']."','".$item['id_prodi']."', '".$item['nama_lengkap']."', '".$item['nama_tampilan']."', '".$item['nip']."', '".$item['password']."', 
       '".$item['name']."', '".$item['email']."')");
     mysql_close();
     echo "Data Berhasil Disimpan...";
     }else{
     echo "Data Gagal, Tersimpan...";
     }
?>

Please help me...

  • 写回答

2条回答 默认 最新

  • dqrsceg6279196 2014-11-12 17:06
    关注

    Edit: try this instead:

    if (!is_array($data) || count($data) != 1)
        exit(); // Error handling
    $item = $data[0];
    mysql_query("INSERT INTO tb_database
        VALUES ('".$item['id_peneliti']."','".$item['id_prodi']."',
        '".$item['nama_lengkap']."', '".$item['nama_tampilan']."',
        '".$item['nip']."', '".$item['password']."',
        '".$item['name']."', '".$item['email']."')");
    

    That should be enough. But you should escape your datas before inserting, or use prepared statements with PDO to prevent SQL injection.

    评论

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line