insert data into mysql from json encoded data (pinterest api oauth) using php

时间:2016-04-04 18:38:45

标签: php mysql json oauth pinterest

I have user information in json format retrieved from pinterest api (oauth)

$me = $pinterest->users->me(array(
'fields' => 'username,first_name,last_name,image[large]'
));

when I print (echo) data using json decode

$array_data = json_decode($me); 
echo "<pre/>";print_r($array_data);

foreach ($array_data as $key=>$value){

    if($key == 'image'){
        echo $key. " url is=" . $value->large->url .'<br/>';
    }else{

        echo $key. "=" . $value .'<br/>';
    }
}
}

result :

stdClass Object
(
[id] => 195414208739840616
[username] => rajivsharma033
[first_name] => Rajiv
[last_name] => Sharma
[bio] => 
[created_at] => 
[counts] => 
[image] => stdClass Object
    (
        [large] => stdClass Object
            (
                [url] => https://s-media-cache-ak0.pinimg.com/avatars/rajivsharma033_1459712414_280.jpg
                [width] => 280
                [height] => 280
            )

    )

)

id=195414208739840616
username=rajivsharma033
first_name=Rajiv
last_name=Sharma
bio=
created_at=
counts=
image url is=https://s-media-cache- 
ak0.pinimg.com/avatars/rajivsharma033_1459712414_280.jpg

Now I want to insert that data into MySQL. how to do it. I have tried:

$query = "INSERT INTO pinterest(pin_id) VALUES" .$value;
 $query_signup = mysqli_query($MySQLi_CON, $query);

but It is showing error :

Catchable fatal error: Object of class stdClass could not be converted to string in G:\XAMPP\htdocs\a\pinterestlogin\callback.php on line 38

Help Me.

1 个答案:

答案 0 :(得分:0)

$value is an object when it's hitting the element with index 'image' as you iterate your decoded pintrest content array. Your Mysql insert expects a string, not an object.

First, I'd recommend calling json_decode with true, to convert everything to associative arrays, unless you need to treat something in the body as an object.

$array_data = json_decode($me, true);`

Then check when $value is an object or an array and prior to your mysql insert either:

  • Convert the images object to a json string and store that $value = json_encode($value);
  • Serialize the image object $value = serialize($value);;