简体   繁体   English

PHP通过curl获取数据并插入SQL数据库

[英]PHP get data via curl and insert into SQL database

I have a few questions about my code for creating a local replica of the client database via CURL GET. 我对通过CURL GET创建客户端数据库的本地副本的代码有一些疑问。

Situation: 情况:

  • I need to create local replica databases with 1.5mil records via curl 我需要通过curl创建具有150万条记录的本地副本数据库
  • Url address is generating a script. 网址正在生成脚本。 Url addresses consist of parameters SINCE, LASTID, ACCESS_TOKEN like https://CLIENT_SERVER_URL/sync?last_id=LAST_ID&since=ISO_8601_TIMESTAMP&access_token=TOKEN 网址由参数SINCE,LASTID,ACCESS_TOKEN组成,例如https://CLIENT_SERVER_URL/sync?last_id=LAST_ID&since=ISO_8601_TIMESTAMP&access_token=TOKEN
  • One curl call generates 100 records 一次curl调用可生成100条记录
  • Access to the client server is limited to 60 accesses per minute 对客户端服务器的访问限制为每分钟60次访问
  • Script to be run every day and synchronize databases 每天运行并同步数据库的脚本

What I have problem with and I need to advise 我有什么问题需要咨询

  • Q1.) BFU question (sorry), How do I generate timestamp in this format 2016-06-22T23%3A34%3A20.169659Z ? Q1。)BFU问题(对不起),如何生成这种格式的时间戳记2016-06-22T23%3A34%3A20.169659Z Timestamp must generate the CURRENT_DATE - 1 day 时间戳记必须产生CURRENT_DATE - 1 day

  • Q2.) How do I create a loop to script repeatedly generate new URLs and store the records in the database? Q2。)我如何创建一个循环以脚本重复生成新的URL并将记录存储在数据库中?

  • Q3.) How can I limit calls to only 60 calls per minute? Q3。)如何将通话限制为每分钟只能通话60次?

  • Q4.) How do I make a INSERT into the database so that the entry is inserted when it does not exist or UPDATEd when it exists? Q4。)如何对数据库进行INSERT,以便在不存在该条目时将其插入,而在存在该条目时则进行UPDATE?

My PHP code 我的PHP代码

<?php 
// select DB
$servername = "MY_DATABASE";
$username = "USER";
$password = "PASS";
$dbname = "DB_NAME";

// Create connection
$corporateBodies = new mysqli($servername, $username, $password, $dbname);

$sql = "SELECT id FROM my_table ORDER BY id DESC LIMIT 1";
$lastID = $corporateBodies->query($sql);
$lastID = mysqli_fetch_array($lastID);

$base = "CLIENT_SERVER_URL/";
$since = "GENERATED_TIMESTAMP";
$accessToken = "ACCESS_TOKEN";
$url = $base . "sync?last_id=" . $lastID["id"] . "&since=" . $since . "&access_token=" . $accessToken;

//function httpGet($url) {
    $crl = curl_init($url); 
    curl_setopt($crl,CURLOPT_URL,$url);
    curl_setopt($crl,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($crl,CURLOPT_HEADER, false);
    curl_setopt($crl, CURLOPT_TIMEOUT, 60); 
    $reply =curl_exec($crl);

    curl_close($crl);

    //decoding the json data
    $decoded_data = json_decode($reply, true);

    $insertArray = $corporateBodies->prepare(
    "INSERT INTO my_table (
        id,
            cin,
            tin,
            vatin,
            name,
            formatted_address,
            street,
            reg_number,
            building_number,
            postal_code,
            municipality,
            country,
            established_on,
            terminated_on,
            vatin_paragraph,
            registration_office,
            registration_number,
            formatted_street,
            street_number,
            created_at,
            updated_at
    )
    VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
    );

    $corporateBodies->query("START TRANSACTION");

    foreach ($decoded_data as $row) {
    $bind = $insertArray->bind_param('iiissssisisssssssssss',
            $row['id'],
            $row['cin'],
            $row['tin'],
            $row['vatin'],
            $row['name'],
            $row['formatted_address'],
            $row['street'],
            $row['reg_number'],
            $row['building_number'],
            $row['postal_code'],
            $row['municipality'],
            $row['country'],
            $row['established_on'],
            $row['terminated_on'],
            $row['vatin_paragraph'],
            $row['registration_office'],
            $row['registration_number'],
            $row['formatted_street'],
            $row['street_number'],
            $row['created_at'],
            $row['updated_at']
    );

    $exec = $insertArray->execute();

    // Close the prepared statement
    $insertArray->close();

    $commit = $corporateBodies->query("COMMIT");

    $corporateBodies->close();
?>

your timestamp perfectly matches an ISO8601 with Z instead of +00:00 , and microsecond precision, so to create your timestamp - 1 day, would probably be 您的时间戳与Z而不是+00:00和微秒精度完全匹配ISO8601,因此要创建时间戳-1天,可能是

$stamp=(new DateTime('-1 day',new DateTimeZone("UTC")))->format('Y-m-d\TH:i:s.u\Z');

quote How do I create a loop to script repeatedly generate new URLs and store the records in the database? quote How do I create a loop to script repeatedly generate new URLs and store the records in the database? if you're wondering how to create a loop, 如果您想知道如何创建循环,

for($i=0;$i<60;++$i){/*code in here will be looped 60 times!*/}

if you're wondering to to generate the new URLs, check the API docs, we can't answer that question without knowing how the API works, and you didn't include the api specs in your question. 如果您想生成新的URL,请查看API文档,如果您不知道API的工作原理,我们将无法回答该问题,并且您没有在问题中包含api规范。

if you're wondering how to store something in a database, that depends on your database, we can't answer that question without knowing what kind of database you're using. 如果您想知道如何在数据库中存储某些内容(取决于您的数据库),那么我们在不知道您使用哪种数据库的情况下就无法回答该问题。 but assuming you're using an SQL database (as opposed to a NoSQL database like MongoDB, or some other database), its usually through an insert statement, like 但是假设您使用的是SQL数据库(而不是像MongoDB这样的NoSQL数据库或其他一些数据库),则通常是通过插入语句,例如

INSERT INTO records VALUES('new record');

quote How can I limit calls to only 60 calls per minute? quote How can I limit calls to only 60 calls per minute?

while(!$finished){
$quota_reset_time=microtime(true)+60;
for($i=0;$i<60;++$i){
//code in here runs 60 times
}
@time_sleep_until($quota_reset_time); // this line sleeps until 60 seconds has passed since $quota_reset_time was set.
}

the code inside the for loop would run at a maximum speed of 60 times per minute. for循环中的代码将以每分钟60次的最高速度运行。

quote Q4.) How do I make a INSERT into the database so that the entry is inserted when it does not exist or UPDATEd when it exists? 引用Q4.) How do I make a INSERT into the database so that the entry is inserted when it does not exist or UPDATEd when it exists?

again, it depends on the database. 同样,它取决于数据库。 assuming a MySQL or MariaDB database, though, make the value an UNIQUE column, and make an INSERT OR REPLACE statement, like 但是,假设使用MySQL或MariaDB数据库,则将值设为UNIQUE列,并INSERT OR REPLACE语句,例如

INSERT OR REPLACE INTO tbl(`value`,`last_update_time`)
VALUES('FOO',NOW());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM