PHP将嵌套的json插入mySQl

时间:2018-03-07 21:29:05

标签: php mysql json

我试图将嵌套的json从URL插入mySQL。

我已经按照其他问题/答案尝试了一些foreach,但似乎无法让它发挥作用。我已经给它一个带有for循环的它然后插入但它只插入1个记录,这是最后一个。

有3个第一级数组元素(formguide,团队,玩家),我只想从formguide中获取值。

从URL返回的示例JSON:

{ 

"formguide": [
{
    "SUSPENSION": null,
    "WEEKPOINTS": "7",
    "TEAMCODE": "LIV",
    "VALUE": "4.5",
    "POINTS": "215",
    "PLAYERNAME": "Salah, M",
    "TEAMNAME": "Liverpool",
    "SIXWEEKPOINTS": "58",
    "INJURY": null,
    "PLAYERID": "3324",
    "POS": "MID"
    },
    {
    "SUSPENSION": null,
    "WEEKPOINTS": "8",
    "TEAMCODE": "TOT",
    "VALUE": "7.0",
    "POINTS": "209",
    "PLAYERNAME": "Kane, H",
    "TEAMNAME": "Tottenham Hotspur",
    "SIXWEEKPOINTS": "49",
    "INJURY": null,
    "PLAYERID": "4002",
    "POS": "STR"
    },

我的代码:

<?php
$servername = "localhost";
$username = "root";
$password = "pass";
$dbname = "my_db";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

include('simple_html_dom.php');

$url = file_get_contents('https://insertjsonURL.com');
$array = json_decode($url, true);
$length = count($array['formguide']);

//assign array keys to variables for sql insert query
for ($i = 0; $i < $length; $i++) {
$sus = $array['formguide'][$i]['SUSPENSION'];
$wpoints = $array['formguide'][$i]['WEEKPOINTS'];
$tcode = $array['formguide'][$i]['TEAMCODE'];
$val = $array['formguide'][$i]['VALUE'];
$points = $array['formguide'][$i]['POINTS'];
$pname = $array['formguide'][$i]['PLAYERNAME'];
$tname = $array['formguide'][$i]['TEAMNAME'];
$sixwpoints = $array['formguide'][$i]['SIXWEEKPOINTS'];
$injury = $array['formguide'][$i]['INJURY'];
$playerid = $array['formguide'][$i]['PLAYERID'];
$pos = $array['formguide'][$i]['POS'];
}

$sql = "INSERT INTO formguide (suspension, weekpoints, teamcode, value, points, playername, teamname, sixweekpoints, injury, playerid, pos)
VALUES ('$sus', '$wpoints', '$tcode','$val','$points','$pname','$tname','$sixwpoints','$injury','$playerid','$pos')";


//output message if successful or not
if (mysqli_query($conn, $sql)) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

mysqli_close($conn);
?>

如上所述,我从下面尝试了foreach,但似乎都没有奏效。不确定这与我通过URL检索json有什么关系?这是我能看到的主要区别。 Poiz answerAnkiiG answer

2 个答案:

答案 0 :(得分:1)

问题很简单。您的insert语句在for语句之外,导致它只插入数组的最后一个元素,因此将其修复为:

for ($i = 0; $i < $length; $i++) { 
    $sus = $array['formguide'][$i]['SUSPENSION'];
    $wpoints = $array['formguide'][$i]['WEEKPOINTS'];
    $tcode = $array['formguide'][$i]['TEAMCODE'];
    $val = $array['formguide'][$i]['VALUE'];
    $points = $array['formguide'][$i]['POINTS'];
    $pname = $array['formguide'][$i]['PLAYERNAME'];
    $tname = $array['formguide'][$i]['TEAMNAME'];
    $sixwpoints = $array['formguide'][$i]['SIXWEEKPOINTS'];
    $injury = $array['formguide'][$i]['INJURY'];
    $playerid = $array['formguide'][$i]['PLAYERID'];
    $pos = $array['formguide'][$i]['POS'];

    $sql = "INSERT INTO formguide (suspension, weekpoints, teamcode, 
                          value, points, playername, teamname, 
                          sixweekpoints, injury, playerid, pos)
            VALUES ('$sus', '$wpoints', '$tcode','$val','$points','$pname','$tname',
         '$sixwpoints','$injury','$playerid','$pos')";

  //output message if successful or not
  if (mysqli_query($conn, $sql)) {
      echo "New record created successfully";
  } else {
      echo "Error: " . $sql . "<br>" . mysqli_error($conn);
  }
}

答案 1 :(得分:0)

如果我理解正确,它只会在数组中插入最后一个对象,因为只有一个sql语句正在执行,它位于for语句之后。因此,变量$sus$wpoints 正在使用数组中 last 对象的值进行设置 - 在您的示例中,它将添加只有“ Kane,H ”播放器的数据。

对于每个对象,您需要创建一个SQL语句,以便将其添加到数据库中。为此,请将$sql变量移至for语句并使用concatenating assignment operator,以便为$sql变量中的每个元素集创建一个SQL语句。

$sql = "INSERT INTO formguide (suspension, weekpoints /* ... the field names*/) VALUES"; 
for ($i = 0; $i < $length; $i++) {
  $sus = $array['formguide'][$i]['SUSPENSION'];
  $wpoints = $array['formguide'][$i]['WEEKPOINTS'];
  // The other variables . . .
  $sql .= "('$sus', '$wpoints' /* The other variables*/),";
}

您可以看到inserting multiple rows in MySQL in this link.


修改

作为评论中提到的Jorge Campos$sql变量将有一个备用逗号,会导致错误。要更正此错误,您可以删除备用逗号,如下所示。

$sql = "INSERT INTO formguide (suspension, weekpoints /* ... the field names*/) VALUES"; 
for ($i = 0; $i < $length; $i++) {
  $sus = $array['formguide'][$i]['SUSPENSION'];
  $wpoints = $array['formguide'][$i]['WEEKPOINTS'];
  // The other variables . . .
  $sql .= "('$sus', '$wpoints' /* The other variables*/),";
}
$pos = strrpos($sql, ","); // Last occurrence of ',' in $sql
$sql = substr($sql, 0, $pos);// Remove the last ','

但是我会选择Jorge Campos的答案,因为它需要较少的处理资源,但还有另一个想法。