使用php将嵌套数组中的数据插入mysql

使用php将嵌套数组中的数据插入mysql,php,mysql,arrays,json,Php,Mysql,Arrays,Json,我有这个json数据的嵌套数组,我正在尝试将特定数据插入MYSQL数据库。然而,我得到了一个错误,我只是不知道我的代码有什么问题。很抱歉,php/mysql还是新手。谢谢你的帮助 以下是json数组: [ { "title": "★ (Blackstar)", "artist": "David Bowie", "year": "2016", "genre": "Jazz", "media": [ { "totalDiscs": "1", "position": "1", "tracks":

我有这个json数据的嵌套数组,我正在尝试将特定数据插入MYSQL数据库。然而,我得到了一个错误,我只是不知道我的代码有什么问题。很抱歉,php/mysql还是新手。谢谢你的帮助

以下是json数组:

[
{
"title": "★ (Blackstar)",
"artist": "David Bowie",
"year": "2016",
"genre": "Jazz",
"media": [
{
"totalDiscs": "1",
"position": "1",
"tracks": [
{
"title": "★ (Blackstar)",
"number": "1",
"artists": []
},
{
"title": "'Tis A Pity She Was A Whore",
"number": "2",
"artists": []
},
{
"title": "Lazarus",
"number": "3",
"artists": []
},
{
"title": "Sue (Or In A Season Of Crime)",
"number": "4",
"artists": []
},
{
"title": "Girl Loves Me",
"number": "5",
"artists": []
},
{
"title": "Dollar Days",
"number": "6",
"artists": []
},
{
"title": "I Can't Give Everything Away",
"number": "7",
"artists": []
}
]
}
],
"score": 1
}
]
这是我的密码:

$json = json_decode($result, true);

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "4tracks";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} else {
    //echo "connected <br/>";
}   



$sql = "INSERT INTO tracks (artist_name)
VALUES ('".$json[0]['artist']."')";

    if (array_key_exists('genre',$json[0])){
        $sql = "INSERT INTO tracks (track_genre)
            VALUES ('".$json[0]['genre']."')";

    }

    foreach($json[0]['media'] as $key => $values){


        foreach($values['tracks'] as $key1 => $values1) {
            $sql .= "INSERT INTO tracks (track_name)
                VALUES ('".$values1['title']."')";


        }
}



if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
$json=json\u decode($result,true);
$servername=“localhost”;
$username=“root”;
$password=“”;
$dbname=“4track”;
//创建连接
$conn=newmysqli($servername、$username、$password、$dbname);
//检查连接
如果($conn->connect\u错误){
die(“连接失败:”.$conn->connect\U错误);
}否则{
//回声“已连接
”; } $sql=“插入曲目(艺术家姓名) 值(““$json[0]['Artister']。”)”; 如果(数组键存在('genre',$json[0])){ $sql=“插入曲目(曲目类型) 值(““$json[0][“流派”]。”)”; } foreach($json[0]['media']作为$key=>$value){ foreach($value['tracks']作为$key1=>$values1){ $sql.=“插入曲目(曲目名称) 值(““$values1['title']”.“)”)”; } } if($conn->query($sql)==TRUE){ echo“新记录创建成功”; }否则{ echo“Error:”.$sql.“
”$conn->Error; } $conn->close();
下面是我在wamp上运行.php时的输出:

错误:在曲目(艺人名称)中插入值('David Bowie');插入 进入曲目(曲目类型)值(“爵士乐”)

在轨迹(轨迹名称)中插入值('★ (黑星)",

插入曲目(曲目名称)值(“很遗憾她是一个 妓女),

在轨道(轨道名称)中插入值(“Lazarus”)

在曲目(曲目名称)中插入值('Sue(或在一个音乐季) 犯罪),

插入曲目(曲目名称)值(“女孩爱我”)

在轨道(轨道名称)中插入值(“美元天数”)

插入曲目(曲目名称)值('我不能给出所有内容 离开);

您的SQL语法有错误;检查手册 对应于您的MySQL服务器版本,以便使用正确的语法 “近”插入曲目(曲目类型)值(“爵士乐”);插入 轨道(2号线轨道)---

问题是,你需要避开那句话

$sql = "INSERT INTO tracks (artist_name)
VALUES ('". addslashes ($json[0]['artist']) ."');";

转义将确保MySQL不会解析任何特殊符号(如“JSON中的符号”)

要转义查询,请使用
$mysqli->real\u escape\u string($my\u json);


无论您试图插入到数据库中的内容是什么,都要进行转义。或者更好的做法是使用参数化或准备好的语句(阅读更多内容)。

最明显的问题是,您正在构建一个包含多个查询的字符串。虽然可以使用
mysqli\ucode>执行多个查询,但不能使用
->query()
方法,独立执行每个查询会更简单

此外,当您可以在一个查询中同时向一个表插入多个列时,您正在
跟踪
表中的每列编写一个查询

然后,您需要使用许多循环来循环JSONdata结构,foreach循环最适合于此

另外,如果您使用参数化查询,字符串中的引号问题,如
“title”:“'Tis a遗憾的是她是个妓女”
,将自动为您解决

所以我建议这是一个解决方案

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "4tracks";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    echo "Connection failed: " . $conn->connect_error;
    exit;
}

$j = file_get_contents('tst.json');

$json = json_decode($j);
if (json_last_error() != 0) {
    echo json_last_error_msg();
}

// Notice we prepare the query ONCE, but later execute it many times
// with different data in the parameters

$sql = "INSERT INTO tracks (artist_name, track_genre, track_name) VALUES (?,?,?)";
$stmt = $conn->prepare($sql);
// check the prepare worked, if not report errors and exit
if (! $stmt) {
    echo $conn->error;
    exit;
}
// bind the variables names to the ? place holders
// the variables at this point do not have to exists, or have data in them
$stmt->bind_param('sss', $artist, $genre, $title);


foreach($json as $cd) {

    foreach($cd->media as $media) {

        foreach($media->tracks as $track){

            // load the bound variables with the data for this insert execution
            $artist = $cd->artist;
            $genre = $cd->genre;
            $title = $track->title;

            $result = $stmt->execute();
            // check the insert worked, if not report error
            if (!$result) {
                echo $conn->error;
                exit;
            }
        }
    }
}

您在哪里执行?您使用的是支持多查询执行的函数吗?您还应该使用参数化查询,您永远不知道歌曲/艺术家是否会在其中引用。DB Scheme注意,我认为您希望在
track\u name
中引用艺术家。正如@chris85所说,您的查询实际上是一连串的查询注意,它是在第二个查询开始时随地吐痰。此外,您可以考虑在DB中规范化数据结构。您将JSONSORT转换成PHP数据结构(即JSON-DECODE())?@RiggsFolly我已经编辑了我的帖子。希望我的问题现在更清楚了。看看发生了什么事,即使使用建议也不好,你错过了太多的错误。OP在代码经过一些小的调整后仍然工作!从中学到了很多。谢谢你,先生。干杯!
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "4tracks";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    echo "Connection failed: " . $conn->connect_error;
    exit;
}

$j = file_get_contents('tst.json');

$json = json_decode($j);
if (json_last_error() != 0) {
    echo json_last_error_msg();
}

// Notice we prepare the query ONCE, but later execute it many times
// with different data in the parameters

$sql = "INSERT INTO tracks (artist_name, track_genre, track_name) VALUES (?,?,?)";
$stmt = $conn->prepare($sql);
// check the prepare worked, if not report errors and exit
if (! $stmt) {
    echo $conn->error;
    exit;
}
// bind the variables names to the ? place holders
// the variables at this point do not have to exists, or have data in them
$stmt->bind_param('sss', $artist, $genre, $title);


foreach($json as $cd) {

    foreach($cd->media as $media) {

        foreach($media->tracks as $track){

            // load the bound variables with the data for this insert execution
            $artist = $cd->artist;
            $genre = $cd->genre;
            $title = $track->title;

            $result = $stmt->execute();
            // check the insert worked, if not report error
            if (!$result) {
                echo $conn->error;
                exit;
            }
        }
    }
}