Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Check MySQL Last Row

Tags:

php

mysql

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.

like image 654
Saint Robson Avatar asked Aug 25 '12 16:08

Saint Robson


People also ask

How do I see the last row in MySQL?

To get the last record, the following is the query. mysql> select *from getLastRecord ORDER BY id DESC LIMIT 1; The following is the output. The above output shows that we have fetched the last record, with Id 4 and Name Carol.

How can I get last inserted record in MySQL using PHP?

If you use php to connect to mysql you can use mysql_insert_id() to point to last inserted id.

How do I select the latest record from a table in MySQL?

In SQL Server, we can easily select the last 10 records from a table by using the “SELECT TOP” statement. The TOP clause in SQL Server is used to control the number or percentage of rows from the result. And to select the records from the last, we have to arrange the rows in descending order.

How do I select the last 3 rows in SQL?

I want to select the last 3 rows of an sql table. I know I should use SELECT * FROM table ORDER BY DESC LIMIT 3 , but the problem with this code is that it selects the rows from the end. For example, it selects 30, then 29, then 28. But, I need them in this format: 28, 29, 30 .


2 Answers

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
    }
}
like image 53
newfurniturey Avatar answered Sep 20 '22 13:09

newfurniturey


$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++;
}
like image 39
Mihai Iorga Avatar answered Sep 20 '22 13:09

Mihai Iorga