[英]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? 使用PHP和MySql选择显示数据时,如何获取记录集中最后一行的值? Is there a built in function in MySql or Php to do this? 在MySql或Php中是否有内置函数可以做到这一点?
For Eg (using PDO): 例如(使用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. 这样,您将获得最后5条记录。
I am not that good in PHP but, still... 我的PHP不太好,但是...
I think fetch(PDO::FETCH_ORI_LAST)
best suits your requirement. 我认为fetch(PDO::FETCH_ORI_LAST)
最适合您的要求。
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) 从PHP(PDO)的结果集中获取行
you can order your select descending and limit 1 您可以命令选择降序并限制1
select id from table order by id DESC limit 1 通过ID DESC限制1从表顺序中选择ID
if you want all rows, and just get the last in php, then as @Shamil said, end() works well 如果您想要所有行,并且仅获取php中的最后一行,则正如@Shamil所说,end()效果很好
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.