PHP 检查 MySQL 最后一行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12123933/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP Check MySQL Last Row
提问by Saint Robson
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 :
我有一个关于 PHP 的简单问题来检查这是否是 MySQL 的最后一行。例如我有这个代码:
$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.
我很难检查该行是否是最后一行。知道怎么做吗?谢谢。
回答by newfurniturey
You can use mysql_num_rows()prior to your whileloop, and then use that value for your condition:
您可以mysql_num_rows()在while循环之前使用,然后将该值用于您的条件:
$numResults = mysql_num_rows($result);
$counter = 0
while ($row = mysql_fetch_array($result)) {
if (++$counter == $numResults) {
// last row
} else {
// not last row
}
}
回答by Mihai Iorga
$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
但请考虑 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++;
}
回答by snuffn
Try this:
尝试这个:
$result = mysql_query("SELECT colum_name, COUNT(*) AS `count` FROM table");
$i = 0;
while($row = mysql_fetch_assoc($result))
{
$i++;
if($i == $row['count'])
{
echo 'last row';
}
else
{
echo 'not last row';
}
}
回答by eljoe
$allRows = $stmt->rowCount();
Didn't work for me, had to use:
对我不起作用,必须使用:
$numResults = $result->num_rows;
回答by Pavan BS
$result = //array from the result of sql query.
$key = 1000;
$row_count = count($result);
if($key)
{
if($key == $row_count-1) //array start from 0, so we need to subtract.
{
echo "Last row";
}
else
{
echo "Still rows are there";
}
}
回答by DMIL
Try having a counter inside the while loop and then checking it against mysql_num_rows()
尝试在 while 循环中设置一个计数器,然后根据它进行检查 mysql_num_rows()

