我有一個每 20 分鐘運行一次的 php 腳本(我在 Debian 服務器端使用 screen),
php 腳本使用 LIMIT 1 選擇資料庫的第一行,例如:
$q = mysqli_query($connection,"SELECT * FROM table_name LIMIT 1");
選擇第一行后,它會將結果發送到電報機器人,從資料庫中洗掉第一行,腳本結束。
它每 20 分鐘重復一次此程序,導致螢屏顯示。
現在,問題是,如果我用 LIMIT 1 得到的第一行不符合條件(此時它被洗掉并跳過實際程序直到接下來的 20 分鐘),我怎樣才能讓它選擇第二行(現在又是第一行)使用相同的腳本獲取新資料并避免等待接下來的 20 分鐘?我的實際腳本是否可以使用 LIMIT 1?
uj5u.com熱心網友回復:
顯然我無權訪問你的資料庫,我不知道你的標準是什么,所以這都是偽代碼。我假設如果第一行不符合條件,你會想要洗掉它,但盡可能只跳過它:
$finished = false;
while(!$finished) {
// you already have the code to get the first row. It goes here.
// I will assume those results are in $row
$finished = $row MEETS CRITERIA; // whatever these criteria are
// you also have the code to delete the current row. put that here
// whether this row satisfies the condition or not. The row you
// just selected will always be deleted
}
就這么簡單。如果該行滿足條件,則 $finished 為 TRUE,while 回圈將終止*。如果該行不符合條件,則 $finished 為 FALSE,while 回圈將再次運行。它將一直運行,直到一行滿足條件并且 $finished 為 TRUE。
*!是 php NOT 運算子。它反轉值。所以基本上while回圈的意思是這樣的:
while not finished { do this code }
此外,為了避免非終止回圈,您需要確保結果集中包含某些內容,否則 $finished 永遠不會設定為 TRUE。我不確定你是如何執行的,所以我不打算建議一個實作。請注意,一段時間內可能會成為一個永無止境的回圈并采取措施避免它。例如,您可能會:
$finished = false;
$retries = 5;
while(!$finished && $retries-->0) {
//the code
}
這會減少 $retries 每個回圈,一旦它變為 0,while 將停止。在任何可能意外(或意外)終止的回圈中放置故障保護是個好主意,尤其是在開發程序中,這樣您就不會掛起代碼。
uj5u.com熱心網友回復:
感謝您的回復!
我想我可以使用您的建議,但我需要對其進行編輯,我需要執行的檢查如下:
$q = mysqli_query($connection,"SELECT * FROM table LIMIT 1");
$r = mysqli_fetch_assoc($q);
$e = $r['id'];
$asin_queue = $r['asin'];
$price_queue = $r['new_price'];
//執行檢查以查看價格是否已更改
$r = file_get_contents("https://api.keepa.com/product?asin=$asin_queue&key=$api_keepa");
$gz = gzdecode($r);
$t = json_decode($gz);
//price updated
$new_price = $t->products[0]->csv;
//這里是我卡住的地方我應該做這樣的事情:
while($new_price > $price_queue){
*// 它需要洗掉資料庫的第一行并再次檢查,直到得到正確的條件 $new_price <= $price_queue 然后它可以退出 while 回圈。
//重復以上操作再次檢查*
$q = mysqli_query($connection,"SELECT * FROM table LIMIT 1");
$r = mysqli_fetch_assoc($q);
$e = $r['id'];
$asin_queue = $r['asin'];
$price_queue = $r['new_price'];
//執行檢查以查看價格是否已更改
$r = file_get_contents("https://api.keepa.com/product?asin=$asin_queue&key=$api_keepa");
$gz = gzdecode($r);
$t = json_decode($gz);
//price updated
$new_price = $t->products[0]->csv;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/345922.html
上一篇:逐行比較不同的df并回傳更改
