简体   繁体   中英

How to Insert JSON into mysql table with PHP

I have tried many sites to find how to insert json in mysql but i did not find any proper solution. Can you help me to insert the bellow json in mysql table and also tell me the required names for column in my table.

    {
    "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
    }
}

i need to insert the data : aashiq, App Download - Paytm - Android - IN - Incent from the above json

I will give a try. Bear with me cause my PHP is a bit rusty... So let's say $mydata is you array object storing the JSON. Then:

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

Create a MySQL database with a database called offers with a table offer and three fields: an ID that will be autoincrement, affiliate VARCHAR , final_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());
}

I believe the code above is more or less correct

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM