简体   繁体   中英

Get value of the last record in a record set when using MySql and PHP

When selecting an displaying data using PHP and MySql, how can I get value of the last row in a record set? Is there a built in function in MySql or Php to do this?

For Eg (using PDO):

select id from table limit 5;

Output:
1
2
3
4
5 -> How can I get this value to pass to a function, all things being the same

 while( $row = $stmt->fetch() ) {
   echo $row['id'];

}
 // The value of id of the last row i.e 5 needs to go into a function
       functionName(id value of last row goes here)

How can this be done?

   $last_id = 0
    while( $row = $stmt->fetch() ) {
       echo $row['id'];
       $last_id = $row['id'];
    }
     functionName($last_id)

您可以使用PHP的end($array)获取end($array)的最后一项

尝试MAX()

SELECT max(id) FROM table

Try this...

select id from table ORDER BY id DESC limit 5;

This way you will get last 5 records.

I am not that good in PHP but, still...

I think fetch(PDO::FETCH_ORI_LAST) best suits your requirement.

Example:

$stmt = $conn->query("SELECT firstnme, lastname FROM employee");
$row = $stmt->fetch(PDO::FETCH_ORI_LAST);
print "Name: <p>{$row[0] $row[1]}</p>";

Refer to :
Fetching rows from result sets in PHP (PDO)

you can order your select descending and limit 1

select id from table order by id DESC limit 1

if you want all rows, and just get the last in php, then as @Shamil said, end() works well

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM