PHP/SQL 查询查找最后一个结果 [英] PHP/SQL Query find last result

查看:61
本文介绍了PHP/SQL 查询查找最后一个结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 PHP 中运行 while 循环,以从 mysql 数据库中选择数据.我怎样才能找出最后一条记录是什么,

I am running a while loop in PHP selecting data from a mysql database. How can i find out what the last record is,

例如:

$sql="SELECT * from table1 ";
$rs=mysql_query($sql,$conn);
while($result=mysql_fetch_array($rs))
{
echo $result["col1"].' - '.$result["col2"].'<br>';
}

然后当它到达最后一条记录时,我想将其显示为:

then when it gets to the last record i want to display it like:

echo 'Last Record: '.$result["col1"].' - '.$result["col2"].'<br>';

推荐答案

你基本上需要记录你有多少行,然后设置一个计数器.你可以使用 mysql_num_rows():

You basically need to record how many rows you have, and then set up a counter. You can do that using mysql_num_rows():

$sql="SELECT * from table1";
$rs = mysql_query($sql,$conn);
$numRows = mysql_num_rows($rs);

$i = 1;
while($result=mysql_fetch_array($rs))
{
    echo ($i == $numRows) ? 'Last Record: '.$result["col1"].' - '.$result["col2"].'<br />' : $result["col1"].' - '.$result["col2"].'<br />';
    $i++;
}

您应该注意到 mysql_*() 函数系列现在已被弃用.为了安全和长寿,你真的应该使用 MySQLiPDO.

You should note though that the mysql_*() family of functions is now deprecated. For security and longevity, you really ought to be using MySQLi or PDO.

这篇关于PHP/SQL 查询查找最后一个结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆