我有一个关于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*/}
}
我很难检查该行是否是最后一行。知道怎么做吗?感谢。
答案 0 :(得分:40)
您可以在while
循环之前使用mysql_num_rows()
,然后根据您的条件使用该值:
$numResults = mysql_num_rows($result);
$counter = 0
while ($row = mysql_fetch_array($result)) {
if (++$counter == $numResults) {
// last row
} else {
// not last row
}
}
答案 1 :(得分:11)
$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++;
}
但请考虑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++;
}
答案 2 :(得分:2)
试试这个:
$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';
}
}
答案 3 :(得分:1)
import os
directoryname="C:\\Users\\Ineke\\Documents\\Python Scripts\\images"
lijstmetfiles = os.listdir(directoryname)
for i in range(len(lijstmetfiles)):
os.rename(str(lijstmetfiles[i]), str("doggy"+str(i))
没有为我工作,不得不使用:
$allRows = $stmt->rowCount();
答案 4 :(得分:0)
尝试在while循环中使用计数器,然后针对mysql_num_rows()
答案 5 :(得分:0)
$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";
}
}