PHP检查MySQL最后一行

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*/}
}

我有困难来检查当前行是否为最后一行。有什么好的想法吗?谢谢。


1
请勿在新代码中使用mysql_*函数。它们已不再维护,社区已经开始弃用过程。看看红框? 相反,您应该了解预处理语句,并使用PDOMySQLi。如果您无法决定,本文将有所帮助。如果您想学习,这是一个很好的PDO教程 - Mihai Iorga
重点在于 /* 在这里做些什么 */。你是在改变数据还是在打印数据。可能有更好的方法来实现你想要的,而不需要执行迭代条件。 - mickmackusa
6个回答

50

您可以在 while 循环之前使用 mysqli_num_rows() 来获取记录总数,并将该值用作您的条件:

$numResults = mysqli_num_rows($result);
$counter = 0
while ($row = mysqli_fetch_array($result)) {
    if (++$counter == $numResults) {
        // last row
    } else {
        // not last row
    }
}

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++;
}

3
$allRows = $stmt->rowCount();

对我来说没有用,我必须使用:

$numResults = $result->num_rows;

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';
    }
}

0
尝试在while循环内部设置一个计数器,然后将其与mysql_num_rows()进行比较。

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";             
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接