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.
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.
If you use php to connect to mysql you can use mysql_insert_id() to point to last inserted id.
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.
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 .
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
}
}
$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++;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With