php面试上机题(2018-3-3)

需求:将第三方api的前3000条数据全部读取出来,存入对应的数据库字段

第三方api:http://pub.cloudmob.mobi/publisherapi/offers/?uid=92&key=d4bab08884781dbf2bede528e27d243d&limit=1000&page=1

sql代码:

/*
Navicat MySQL Data Transfer

Source Server         : test
Source Server Version : 50714
Source Host           : localhost:3306
Source Database       : test

Target Server Type    : MYSQL
Target Server Version : 50714
File Encoding         : 65001

Date: 2018-03-04 10:02:51
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for offers
-- ----------------------------
DROP TABLE IF EXISTS `offers`;
CREATE TABLE `offers` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `description` text NOT NULL,
  `country` varchar(255) NOT NULL,
  `allowedtraffic` varchar(255) NOT NULL,
  `oid` varchar(10) NOT NULL,
  `avail` varchar(255) NOT NULL,
  `name` varchar(255) NOT NULL,
  `link` text NOT NULL,
  `preview` text NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=25575 DEFAULT CHARSET=utf8;

php代码:

 <?php
 //思路:
 // 1.先通过php的curl将数据取出来,转换为对象
 // 2.连接数据库,做预处理
 // 3.将取出来的值转换为数组,并绑定数据库参数
 // 4.执行sql操作,数据抓取成功
 //ps:数据的初始化及url会话的关闭只能执行一次,所以放在for循环的后面
    $curl = curl_init();
    $page=1;
    for($j=0;$j<3;$j++){
        $url="http://pub.cloudmob.mobi/publisherapi/offers/?uid=92&key=d4bab08884781dbf2bede528e27d243d&limit=1&page=$page";
        // echo $url;
        curl_setopt($curl, CURLOPT_URL,$url );
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($curl);
        // 将json字符串转换为对象
         $data=json_decode($data);
        $con=mysqli_connect("localhost","root","","test");
         if (!$con->connect_error) {
             echo $con->connect_error;
         }
        mysqli_set_charset($con,"gb2312");
        $sql="INSERT INTO offers (description,country,allowedtraffic,oid,avail,name,link,preview)VALUES ( ?,?,?,?,?,?,?,?);";
        $sql_stmt=$con->prepare($sql) or die($con->error);
        for ($i=0; $i <1; $i++) { 
            // 将对象的值转换为数组
            $oid=json_encode($data->data[$i]->oid);
            $avail=json_encode($data->data[$i]->avail);
            $name=json_encode($data->data[$i]->name);
            $link=json_encode($data->data[$i]->link);
            $preview=json_encode($data->data[$i]->preview);
            $allowedtraffic=json_encode($data->data[$i]->allowedtraffic);
            $description=json_encode($data->data[$i]->description);
            $country=json_encode($data->data[$i]->country);
            $sql_stmt->bind_param('ssssssss',$description,$country,$allowedtraffic,$oid,$avail,$name,$link,$preview);
            $b=$sql_stmt->execute();
            }
         if (!$b) {
             echo "操作失败".$sql_stmt->error;
         }else{
             echo "操作成功";
         }
         //释放
            $page=$page+1;
        $con->close();
        } 
    curl_close($curl);
?>
posted @ 2018-03-04 10:19  花花妹子。  阅读(3805)  评论(0编辑  收藏  举报