试图把API数据在数据库与PHP? [英] trying to put api data in database with php?

查看:109
本文介绍了试图把API数据在数据库与PHP?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我拉着从Groupon的API交易,我不知道如何获取数据,并把它与PHP的数据库,我知道如何显示它在HTML中,而不是在数据库中,我需要拉入数据库,所以我必须在信息更多的控制权,如果有人知道如何做到这一点还是知道一个更好的办法,我所有的眼睛的,哈哈,谢谢

 <脚本类型=文/ JavaScript的'>$(函数(){
$ .getJSON(https://api.groupon.com/v2/deals.json?callback=?,
{
    CLIENT_ID:b252ad3634a4ab2985b79d230ccc4e49a3ea9d19
    显示所有,
    division_id:洛 - 洛杉矶
})
.done(功能(数据){
    的console.log(数据);
    //你需要做的,数据的任何处理
    //就在这里,然后砸在DIV
    $。每个(data.deals,功能(I,V){
        $标题= $(< H2 />中,{
            HTML:v.title,
            类:标题
        });
        $ IMG = $(&下; IMG />中,{
            SRC:v.mediumImageUrl
        });
        $交易= $(< D​​IV />中,{
            HTML:v.highlightsHtml + v.pitchHtml
        });
        $(#主)追加($处理);
        。$交易prePEND($标题,$ IMG);
    });
});
});
< / SCRIPT>


解决方案

嗯,我只是要通过启动运行过程...

首先,知道你正在处理和研究这驱动了PHP如何与他们互动。看看这份名单,并开始阅读...
http://www.php.net/manual/en/refs.database.php

将数据发送到一个PHP脚本来处理剩下的,就看你怎么得到的数据。这里有一些基本流程...


  • 使用jQuery拉它,并使用AJAX,你得到它的PHP脚本保存尽快发送。 (需要一个额外的HTTP请求)

  • 使用PHP拉它,将它保存到数据库,然后格式化并在同一页上输出。 (减慢初始页面加载时间)

  • 与jQuery,格式化拉它,并允许用户以preSS一个按钮,然后将阿贾克斯该条目的PHP脚本保存(更灵活,但大大增加了请求)

后,你可以得到你的数据库的连接,你只需要把它保存到使用SQL查询表(最有可能使用INSERT或UPDATE)。随着JSON数据,我preFER将其保存到具有文本数据类型的列。这里唯一的真正的风险是,你必须确保你能验证数据。尤其是如果数据正考虑到PHP在JavaScript / AJAX来源!

时,只使用一个选择SQL语句从该点拉低数据。 PHP的数据库模块将拉动这些数据,并把它变成一个可爱的数组你,使操作方便。

例子

现在,多数民众赞成理论,继承人一些行动。我将要选择的第一个流动的想法。现在,这个人会只是把它保存到数据库中。我没有做任何花哨的检查还是真的拉。但是,这将告诉您如何ajaxing并保存到PHP会工作的想法。

视图deals.html

 <脚本类型=文/ JavaScript的'>$(函数(){
$ .getJSON(https://api.groupon.com/v2/deals.json?callback=?,
{
    CLIENT_ID:b252ad3634a4ab2985b79d230ccc4e49a3ea9d19
    显示所有,
    division_id:洛 - 洛杉矶
})。完成(功能(数据){
    的console.log(数据);
    //你需要做的,数据的任何处理    .post的$('救-deals.php',{dealData:数据},功能(finishData){
         //这是当它已经完成节省用于可选功能
    });    //你格式化随之而来的
    ....
});
< / SCRIPT>

现在,将所有你得到了来自Groupon的数据(完整)发送到使用AJAX调用后一个单独的PHP脚本。我使用后,好了,因为这是它的。

保存-deals.php

  ob_start(); //我喜欢输出缓冲,因为如果我们需要改变标题中期脚本没有死?$ DealData =使用isset($ _ POST ['dealData'])$ _ POST ['dealData']:死(格式不正确的表格数据!);如果($ DealData!=''){
   $ DB =新的mysqli(example.com,用户,密码,数据库);
   如果($ DB-GT&; connect_errno){
      回声无法连接到MySQL:。 $ DB-GT&; connect_error;
   }   $ DealData = $ DB-GT&; real_escape_string($ DealData); //消毒它为MySQL   如果($ DB-GT&;!查询(INSERT INTO交易(数据)VALUES($ DealData)){
      回声插入失败:($ DB-GT&;错误号。)。 $ DB-GT&;误差;
   }其他{
      //在这一点上应该已经插入了!
      //你可以返回一个字符串的成功,或任何你现在想。
   }
}其他{
   http_response_ code(400);
   死亡(错误的请求,请再次检查您的输入,并尝试);
}
ob_end_flush()函数; //关闭了输出缓冲

要注意的是脚本的一些重要的事情是,ob_ *功能是完全可选的。 DealData设置的方法是检查后数据包含的价值,并正确设置它非常简便方法;如果没有,则得到一个错误。

这下一个脚本是向您展示如何从数据库中提取数据,现在,操纵它,如果你想要的。这也将返回数据作为JSON信息,因此它可以利用JavaScript $使用。的getJSON()电话。这主要是参考一个片段

操纵-deals.php

  //首先连接到数据库!
$ DB =新的mysqli(example.com,用户,密码,数据库);
如果($ DB-GT&; connect_errno)死亡(无法连接到MySQL:$ DB-GT&; connect_error);//获取所有条目!
如果($结果= $ DB-GT&;!查询(SELECT * FROM数据))死亡(无法检索数据!$ DB-方式>错误);//德code中的DATAS!
$ returnResults = [];
而($项= $结果> FETCH_ASSOC()){
   $ JSON = json_de code($入门['数据']);   //操纵自己的喜好!
   $ JSON-> whatever->标签[1] - >你 - >想=任何价值;   //将它添加到的结果!
   $ returnResults [] = $ JSON;
}
回声json_en code($ returnResults);

这是最后一节只是为了好玩。这将导出包含结果数组的JSON字符串。而且每个数组的条目将是一个有效的对象,就像Groupon的给了你。希望帮助!

I'm pulling deals from Groupon's api, and I have no clue how to take the data and put it into a database with php, i know how to show it on in html, but not in the database, I need to pull it into the database so I have more control over the info, if anybody knows how to do this or knows a better way, i'm all eye's, lol, thanks

<script type='text/javascript'>

$(function () {
$.getJSON("https://api.groupon.com/v2/deals.json?callback=?", 
{
    client_id: "b252ad3634a4ab2985b79d230ccc4e49a3ea9d19",
    show: "all",
    division_id: "los-angeles"
})
.done(function (data) {
    console.log(data);
    // do whatever processing you need to do to the data
    // right here, then drop it in the div
    $.each(data.deals, function (i, v) {
        $title = $("<h2/>", {
            html: v.title,
            class: "heading"
        });
        $img = $("<img/>", {
            src: v.mediumImageUrl
        });
        $deal = $("<div/>", {
            html: v.highlightsHtml + v.pitchHtml
        });
        $("#main").append($deal);
        $deal.prepend($title, $img);
    });
});
});
</script>

解决方案

Theory

Well I'm just gonna start running through the process...

First, know which driver you are dealing with and research how PHP interacts with them. Look at this list and start reading... http://www.php.net/manual/en/refs.database.php

Sending the data to a PHP script to handle the rest, depends on how you got the data. Here are some basic flows...

  • Pull it using jQuery, and use AJAX to send it as soon as you get it to the php script to save it. (Requires an additional HTTP request)
  • Pull it using PHP, save it to the DB, then format and output it on the same page. (Slows down initial page load time)
  • Pull it with jQuery, format it, and allow the user to press a button that will then ajax that entry to the PHP save script (More flexible, but greatly increases requests)

After you can get a connection to your database you just need to save it to a table using a SQL query (most likely using INSERT or UPDATE). With JSON data, I prefer to save it to a column that has the data type of TEXT. The only real risk here is that you have to be sure that you can validate the data. ESPECIALLY IF THE DATA IS BEING GIVEN TO PHP FROM A JAVASCRIPT /AJAX SOURCE!

Pulling the data from that point is just using a "SELECT" sql statement. PHP's database modules will pull this data and put it into a lovely array for you, making manipulation easy.

Examples

Now thats the theory, heres some actions. I'm going to be choosing the 1st flow idea. Now this one will just save it to the database. I'm not doing any fancy checking or really pulling. But this will show you the idea of how ajaxing and saving to php would work.

view-deals.html

<script type='text/javascript'>

$(function () {
$.getJSON("https://api.groupon.com/v2/deals.json?callback=?", 
{
    client_id: "b252ad3634a4ab2985b79d230ccc4e49a3ea9d19",
    show: "all",
    division_id: "los-angeles"
}).done(function (data) {
    console.log(data);
    // do whatever processing you need to do to the data

    $.post('save-deals.php',{dealData: data}, function(finishData) {
         //This is an optional function for when it has finished saving
    });

    // Your formatting comes next
    ....
});
</script>

Now that will send all the data that you got (intact) from groupon to a seperate php script using an AJAX Post call. I use post, well, because that's what it's for.

save-deals.php

ob_start(); //I like output-buffering because if we need to change headers mid script nothing dies

$DealData = isset( $_POST['dealData'] )?$_POST['dealData']:die("Malformed form data!");

if($DealData!='') {
   $DB = new mysqli("example.com", "user", "password", "database");
   if ($DB->connect_errno) {
      echo "Failed to connect to MySQL: " . $DB->connect_error;
   }

   $DealData = $DB->real_escape_string($DealData); //Sanitize it for MySQL

   if (!$DB->query("INSERT INTO deals(data) VALUES ($DealData)") {
      echo "Insert failed: (" . $DB->errno . ") " . $DB->error;
   } else {
      //AT THIS POINT IT SHOULD HAVE BEEN INSERTED!
      //You could return a success string, or whatever you want now.
   }
} else {
   http_response_code("400");
   die("Bad Request, please check your entry and try again");
}
ob_end_flush(); //Close up the output-buffer

Some important things to note about that script is that the ob_* functions are completely optional. The way DealData is set is a VERY shorthand way of checking that the post data contains that value, and setting it properly; if not, then to give an error.

This next script is to show you how to pull the data from the database now, and manipulate it if you want. It will also return the data as JSON information so it can be used with a javascript $.getJSON() call. This is mostly a snippet for reference

manipulate-deals.php

//First connect to the database!
$DB = new mysqli("example.com", "user", "password", "database");
if ($DB->connect_errno) die("Failed to connect to MySQL: " . $DB->connect_error);

//Get ALL the entries!
if(!$results = $DB->query("SELECT * FROM data")) die("Failed to retrieve data! ".$DB->error);

//Decode the datas!
$returnResults = [];
while($entry = $results->fetch_assoc()) {
   $JSON = json_decode($entry['data']);

   //Manipulate however you wish!
   $JSON->whatever->tags[1]->you->want = "whatever value";

   //Add it to the results!
   $returnResults[] = $JSON;
}
echo json_encode($returnResults);

That very last section is just for fun. It would export a json string containing an array of results. And each of that array's entries would be a valid object just as groupon had given you. Hope that helps!

这篇关于试图把API数据在数据库与PHP?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆