2015-09-05 19 views
0

我有這種情況:檢查,如果這是一個while循環中的最後一行或不

while ($row = pg_fetch_row($result)) { 
    if ($this_is_last_row == TRUE) { 
     echo 'yes this is last row'; 
    } else { 
     echo 'no, there is more rows'; 
    } 
} 

是否有可能去檢查每一行「而」循環是否是最後一排與否,不知道行數第一?

+0

可能重複http://stackoverflow.com/questions/13436414/the-last-iteration-in-a- while循環) – Nicolapps

+0

您是否會提供更多信息,作爲分配給變量'this_is_last_row'的值? –

+0

@Nicolapps OP詢問最後一行(來自數據庫表),而不是while循環的最後一次迭代。 –

回答

2

容易:

$last = false; 
while ($row = pg_fetch_row($result)) { 

    $last = $row; 

} 
if ($last !== false) 
{ 
    // this is the last row: 

} 

有沒有其他的方式,通過設置整個結果加強並保持記錄。其餘部分將是最後一個,如果沒有記錄,則爲假。 像往常一樣,結果集不知道後面有多少行。當存在多條記錄時,...fetch_all(...)可能以內存溢出結束。

1

類似的問題被問here

看起來你可以檢索的行數,然後就比較你對電流(也許讓你重複的計數和使用,作爲行號)。

$ number = mysql_num_rows($ sql);

編輯:在您的情況下,它看起來像你想使用:pg_num_rows

+0

mysql? 'pg_'表示postgress .... –

+0

剛剛編輯我的答案爲此,謝謝 – Aocppy

+0

我認爲這是最好的答案。檢查行數,每行增加$ i,如果number是10行,並且$ i = 10那麼這就是最後一行。 – ChrisG

1

哦,只是湊合:

$curr = pg_fetch_row($result); 
while ($curr) { 
    $next = pg_fetch_row($result); 
    if ($next) { 
     echo 'no, there is more rows'; 
    } else { 
     echo 'yes this is last row'; 
    } 
    // use $curr anywhere _before_ this line 
    $curr = $next; 
} 
[在while循環最後一次迭代(的
+0

這會錯過最後一行的單行。 –

+0

@AxelAmthor不會_will_incude最後一行,即使總共有一行。 –

相關問題