【问题标题】:php loops - while or do while?php 循环 - while 或 do while?
【发布时间】:2016-02-21 10:30:30
【问题描述】:

我对 PHP 和 pgsql 还是很陌生……总的来说,对编码还是很陌生。 我想知道是否应该对这个问题执行whiledo while 循环。

我需要查询远程数据源并更新我的数据库,但我受限于每次调用的返回次数。我有超过 1000 行要更新,但我的调用限制是 100。这意味着我需要进行多次调用,直到列中的所有行不再为空。

我相信这是正确的查询,但我的 while 语句是否正确?

这是我的代码:

// $dbconn = connection......
$result = pg_query($dbconn, "WITH data(full_address) AS (VALUES ('location')) 
SELECT full_address FROM $table WHERE latitude is NULL limit 5;");

while ($row = pg_num_rows($result > 0)) {
     $arr = pg_fetch_all($row);

//curl commands fetch data and ingest
}

【问题讨论】:

    标签: php postgresql while-loop php-pgsql


    【解决方案1】:

    如果您希望循环至少运行一次;使用do,但如果你的循环可能永远不会被执行(因为条件),那么使用while

    在您的情况下,while 是首选,因为数据库查询可能没有结果。您的 while 循环需要获取单行并对其进行处理,直到没有更多行可获取。

    while ($row = pg_fetch_row($result)) {
      //your code to use row's data
    }
    

    do-while 循环与 while 循环非常相似,但事实并非如此 表达式在每次迭代结束时检查,而不是在 开始。与常规 while 循环的主要区别在于 do-while 循环的第一次迭代保证运行(事实 表达式仅在迭代结束时检查),而它 可能不一定使用常规的 while 循环运行(事实 在每次迭代开始时检查表达式,如果它 从一开始就计算为 FALSE,循环执行将 立即结束)。

    来自:http://php.net/manual/en/control-structures.do.while.php

    编辑

    // $dbconn = connection......
    for($=0;$i<10;$i++){
    $result = pg_query($dbconn, "**your query with** Limit ".(100*$i).",100;");
        while ($row = pg_fetch_row($result)) {
          //your code to use row's data
          // do your curl stuff here for the 1 result
        }
    }
    

    【讨论】:

    • 循环没有结束.. 它不断循环...$result = pg_query($dbconn, "SELECT full_address FROM $table WHERE latitude is NULL limit 5;"); while ($row = pg_fetch_all($result)) {...
    • 是的,像这样$result = pg_query($dbconn, "SELECT full_address FROM $table WHERE latitude is NULL limit 5;"); while ($row = pg_fetch_all($result)) { $swears = array("full_address" =&gt; "&amp;location", "{" =&gt; "", "}" =&gt; "", "[" =&gt; "", "]" =&gt; "", '"' =&gt; "", ":" =&gt; "="); $json = json_encode($row);
    • while 循环的条件与我的建议不符。您使用的是不同的条件,请尝试使用我建议的代码
    • 据我了解,fetch_row 拉出一行。 $result 是一个行数组,所以不应该是 fetch_all 吗?
    • 那为什么要使用循环呢?
    【解决方案2】:

    使用do while id 循环应该至少执行一次。

    While是进入控制循环(它会在你进入循环时检查条件)

    Do While 是退出控制循环(循环执行一次后会检查条件)

    【讨论】:

      猜你喜欢
      • 2021-07-18
      • 2021-07-27
      • 2015-02-16
      • 1970-01-01
      • 1970-01-01
      • 2018-05-09
      • 2015-07-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多