19

我有一个关于 PHP 的简单问题来检查这是否是 MySQL 的最后一行。例如我有这个代码:

$result = mysql_query("SELECT *SOMETHING* ");

while($row = mysql_fetch_array($result))
{
if (*this is the last row*)
{/* Do Something Here*/}
else
{/* Do Another Thing Here*/}
}

我很难检查该行是否是最后一行。知道怎么做吗?谢谢。

4

6 回答 6

50

您可以在循环mysqli_num_rows()之前while使用,然后将该值用于您的条件:

$numResults = mysqli_num_rows($result);
$counter = 0
while ($row = mysqli_fetch_array($result)) {
    if (++$counter == $numResults) {
        // last row
    } else {
        // not last row
    }
}
于 2012-08-25T17:01:21.483 回答
11
$result = mysql_query("SELECT *SOMETHING* ");

$i = 1;
$allRows = mysql_num_rows($result);
while($row = mysql_fetch_array($result)){

    if ($allRows == $i) {
        /* Do Something Here*/
    } else {
        /* Do Another Thing Here*/}
    }
    $i++;
}

但请考虑 PDO

$db = new PDO('mysql:host=localhost;dbname=testdb', 'username', 'password');
$stmt = $db->query("SELECT * FROM table");
$allRows = $stmt->rowCount();
$i = 1;
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {

    if ($allRows == $i) {
        /* Do Something Here*/
    } else {
        /* Do Another Thing Here*/}
    }
    $i++;
}
于 2012-08-25T17:01:39.577 回答
3
$allRows = $stmt->rowCount();

对我不起作用,不得不使用:

$numResults = $result->num_rows;
于 2015-10-22T15:09:40.013 回答
2

尝试这个:

$result = mysql_query("SELECT colum_name, COUNT(*) AS `count` FROM table");

$i = 0;

while($row = mysql_fetch_assoc($result))
{
    $i++;

    if($i == $row['count'])
    {
        echo 'last row';
    }
    else
    {
        echo 'not last row';
    }
}
于 2012-08-25T17:02:51.810 回答
0

尝试在while循环中有一个计数器,然后检查它mysql_num_rows()

于 2012-08-25T17:02:23.173 回答
0
$result = //array from the result of sql query.
$key = 1000; 
$row_count = count($result); 
if($key)
{
    if($key == $row_count-1)  //array start from 0, so we need to subtract.
    {
       echo "Last row";             
    }
    else
    {
       echo "Still rows are there";             
    }
}
于 2019-01-25T06:54:20.113 回答