dsa89029 2015-11-19 02:56
浏览 438
已采纳

JSON数组到MySQL数据库

I'm working on a project that involves a PHP script that calls an API and gets a JSON array. I then want to put this JSON array into a MySql database. The issue I am running into is that while the script executes without any errors or exceptions in the terminal, my database is not filling with any data.

I am running MySQL Workbench as my MySQL client and have created a schema called "team_data" into which I am attempting to input my JSON array. I have removed my API key for obvious reasons. Any ideas where I am going wrong here?

<?php

$con = mysql_connect("127.0.0.1","XXXXXX","XXXXXX") or die('Could not connect: ' . mysql_error());
    mysql_select_db("test1", $con);

$json = file_get_contents('team_data.json');    
$data = json_decode($json, true);

foreach($data as $row)
{

    $game = $data['nfl_game_id'];
    $team = $data['team'];
    $opponent = $data['opponent'];
    $totfirstdown = $data['totalfirstdown'];
    $totyds = $data['totyds'];
    $pyds = $data['pyds'];
    $ryds = $data['ryds'];
    $pen = $data['pen'];
    $penyds = $data['penyds'];
    $trnovr = $data['trnovr'];
    $pt = $data['pt'];
    $ptyds = $data['ptyds'];
    $ptavg = $data['ptavg'];

    $sql = "INSERT INTO Teams(nfl_game_id, team, opponent, totalfd, totyds, pyds, ryds, pen, penyds, trnovr, pt, ptyds, ptavg);
    VALUES('$game', '$team', '$opponent', '$totfirstdown', '$totyds', '$pyds', '$ryds', '$pen', '$penyds', '$trnovr', '$pt', '$ptyds', '$ptavg')";

    mysql_query($sql,$con);

}



?>
  • 写回答

2条回答

  • dongqiangou5724 2015-11-19 03:29
    关注
    • Error from your comment, after I suggested you check for errors on your query:

    You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '; VALUES('', '', '', '', '', '', '', '', '', '', '', '', '')' at line 1

    The error shows you where it starts right syntax to use near '; < right there.

    ... ptyds, ptavg); < see that semi-colon? Remove it. It's an end of statement character.

    However, you're doing foreach($data as $row) but not using $row.

    You need to change all $data['xxx'] to $row['xxx'] which is why your values are empty.

    If there are any characters that MySQL will complain about, then you will need to escape your data. Any which way, it's best that you do.

    As a bonus answer:

    Your present code is open to SQL injection. Use mysqli_* with prepared statements, or PDO with prepared statements.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)