【问题标题】:insert data into mysql from json encoded data (pinterest api oauth) using php使用php将数据从json编码数据(pinterest api oauth)插入mysql
【发布时间】:2016-04-05 02:51:08
【问题描述】:

我有从 pinterest api (oauth) 检索到的 json 格式的用户信息

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

当我使用 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/>';
    }
}
}

结果:

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

现在我想将该数据插入 MySQL。怎么做。 我试过了:

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

但它显示错误:

可捕获的致命错误:类 stdClass 的对象无法在第 38 行的 G:\XAMPP\htdocs\a\pinterestlogin\callback.php 中转换为字符串

帮帮我。

【问题讨论】:

  • 您应该将来自 API 的数据视为用户提交的数据并验证,然后使用准备好的语句。未经验证然后使用准备好的语句,不得让用户提交的或第3方的数据靠近您的数据库

标签: php mysql json oauth pinterest


【解决方案1】:

$value 是一个对象,当您迭代解码的 pintrest 内容数组时,它会碰到索引为 'image' 的元素。您的 Mysql 插入需要一个字符串,而不是一个对象。

首先,我建议使用 true 调用 json_decode,将所有内容转换为关联数组,除非您需要将主体中的某些内容视为对象。

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

然后检查 $value 何时是一个对象或一个数组,并且在你的 mysql 插入之前:

  • 将图像对象转换为json字符串并存储$value = json_encode($value);
  • 序列化图片对象$value = serialize($value);;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-17
    • 1970-01-01
    • 2018-12-27
    • 2020-11-23
    • 1970-01-01
    • 2014-03-13
    • 2013-11-14
    • 1970-01-01
    相关资源
    最近更新 更多