Saint Robson
Saint Robson

Reputation: 5525

PHP Check MySQL Last Row

I have a simple question regarding PHP to check if this is the last row of MySQL or not. For example I have this code :

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

I have difficulties to check if the row is the last one or not. Any idea how to do it? Thanks.

Upvotes: 19

Views: 39644

Answers (6)

newfurniturey
newfurniturey

Reputation: 38416

You can use mysqli_num_rows() prior to your while loop, and then use that value for your condition:

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

Upvotes: 50

Pavan BS
Pavan BS

Reputation: 11

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

Upvotes: 0

eljoe
eljoe

Reputation: 168

$allRows = $stmt->rowCount();

Didn't work for me, had to use:

$numResults = $result->num_rows;

Upvotes: 3

snuffn
snuffn

Reputation: 2122

Try this:

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

Upvotes: 2

DMIL
DMIL

Reputation: 703

Try having a counter inside the while loop and then checking it against mysql_num_rows()

Upvotes: 0

Mihai Iorga
Mihai Iorga

Reputation: 39704

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

but please take in consideration 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++;
}

Upvotes: 11

Related Questions