码迷,mamicode.com
首页 > 数据库 > 详细

php定时执行请求,并存入数据库

时间:2019-03-04 11:23:14      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:模式   password   没有   name   ESS   into   exce   time   ++   

//数据请求
//$t1 =  time();
$i=0;
do{
    $url = ‘‘;
    $ch = curl_init();
    $timeout = 5;
    curl_setopt ($ch, CURLOPT_URL, $url);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $file_contents = curl_exec($ch);
    curl_close($ch);
    $res = json_decode($file_contents,true);
    $issue = $res[0][‘issue‘];
    if( !$issue ){
        echo "api wrong";
        $i++;
        sleep(10);
        continue;
    }
    $opendate = $res[0][‘opendate‘];
    $code = $res[0][‘code‘];
    $code = explode(‘,‘,$code);
    $lotterycode = $res[0][‘lotterycode‘];
    $officialissue = $res[0][‘officialissue‘];
    $servername = "127.0.0.1";
    $username = "root";
    $password = "5c28bc46a05afd59";
//    $password = "root";
    $dbname = "onebase";
    try {
        $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
        // 设置 PDO 错误模式,用于抛出异常
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $sql_querry = "select *  from ob_code where issue = ‘".$issue."‘";

        $res= $conn->query($sql_querry);

        if($res->rowCount()!=0){

        }else{
            $sql = "insert into ob_code (issue,opendate,code0,code1,code2,code3,code4,lotterycode,officialissue) values (‘$issue‘,‘$opendate‘,‘$code[0]‘,‘$code[1]‘,‘$code[2]‘,‘$code[3]‘,‘$code[4]‘,‘$lotterycode‘,‘$officialissue‘)";
            // 使用 exec() ,没有结果返回
            $conn->exec($sql);

        }
    }
    catch(PDOException $e)
    {
        echo  "<br>" . $e->getMessage();
    }
    $conn = null;
    $i++;
    sleep(10);
}
while($i<=4);

//$t2 =  time();

//echo ($t2-$t1);

  

 

配合crontab 执行定时任务 可以实现每10秒执行一次此任务。

php定时执行请求,并存入数据库

标签:模式   password   没有   name   ESS   into   exce   time   ++   

原文地址:https://www.cnblogs.com/zetaluoxin/p/10469464.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!