如何使用PHP将JSON插入到mysql表中

时间:2015-10-18 09:14:02

标签: php mysql json

我已经尝试了很多网站来找到如何在mysql中插入json但我没有找到任何正确的解决方案。你能帮我在mysql表中插入波纹管json,并告诉我表格中列所需的名称。

    {
    "request" :  ` {
        "Target" : "Affiliate_Report",
        "Format" : "json",
        "Service" : "HasOffers",
        "Version" : "2",
        "NetworkId" : "network_id",
        "Method" : "getConversions",
        "api_key" : "api_key",
        "fields" : ["Stat.affiliate_info1", "Offer.name"],
        "limit" : "1"
    },
    "response" : {
        "status" : 1,
        "httpStatus" : 200,
        "data" : {
            "page" : 1,
            "current" : 1,
            "count" : 82,
            "pageCount" : 82,
            "data" : [{
                    "Stat" : {
                        "affiliate_info1" : "aashiq"
                    },
                    "Offer" : {
                        "name" : "App Download - Paytm - Android - IN - Incent"
                    }
                }
            ],
            "dbSource" : "branddb"
        },
        "errors" : [],
        "errorMessage" : null
    }
}

我需要从上面的json

插入数据:aashiq, App Download - Paytm - Android - IN - Incent

1 个答案:

答案 0 :(得分:0)

我会试一试。忍受我,因为我的PHP有点生疏...所以让我们说$mydata是存储JSON的数组对象。然后:

$data = $mydata["response"]["data"]; 
$name = $data[0]["Stat"]["affiliate_info1"]; // will store aashiq
$offer = $data[0]["Offer"]["name"]; // will store App Download etc...

使用名为offers的数据库创建一个MySQL数据库,其中包含一个表offer和三个字段:ID将自动增量,affiliate VARCHARfinal_offer VARCHAR

//copying from http://www.kodingmadesimple.com/2014/12/how-to-insert-json-data-into-mysql-php.html?m=1
//connect to mysql db
$con = mysql_connect("localhost","username","password") or die('Could not connect: ' . mysql_error());
//connect to the offers database
mysql_select_db("offers", $con);
//write your Insert query, you omit the autoincrement field and 
//after the keyword VALUES you use your variables enclosed in ''
$sql = "INSERT INTO offer(affiliate, final_offer) VALUES('$name', '$offer'"); 
if(!mysql_query($sql,$con))
{
    die('Error : ' . mysql_error());
}

我相信上面的代码或多或少是正确的