Reputation:
Hi novice to php and mysql. Trying to find how to skip first or last value in a loop of my sql table in descending order? I want to display recently added rows first but not display the last added row.
<tr>
<?php
$page=$_GET['pages']; /* created in index.php(pages.php?pages=m_$title) */
$nage="z_".$page;
$query="SELECT * FROM `$nage` ORDER BY a_id DESC LIMIT 0, 1" ;
$run=mysqli_query($conn,$query);
while($row=mysqli_fetch_array($run)) {
$page_title=$row['title'];
$img_src=$row['img_src'];
// $page_desc=$row['story'];
echo "<tr bgcolor='pink'>
<td style='width:40%'>
<div class='titleDivX'>
<img class='imgFrame'src='$img_src' alt='tasvir'/>
<h5> $page_title</h5>
</div>
</td>
<td bgcolor='yellow'>
<div class='titleDivX'> </div>
</td>
</tr>";
}
?>
Upvotes: 0
Views: 381
Reputation: 1971
You can use a mysqli_num_rows
function described here. If you want to find the first or the last row then you can replace this part of your code
$run=mysqli_query($conn,$query);
while($row=mysqli_fetch_array($run)) {
with this
$run=mysqli_query($conn,$query);
$rowsCount=mysqli_num_rows($run);
$count = 0;
while($row=mysqli_fetch_array($run)) {
$count++;
$isFirst = ($count == 1) ? true : false;
$isLast = ($count == $rowsCount) ? true : false;
Then you can use the $isFirst
and $isLast
variables for the IF statement. For example if you want to skip the last row then you can use a code like this:
<?php
$page=$_GET['pages']; /* created in index.php(pages.php?pages=m_$title) */
$nage="z_".$page;
$query="SELECT * FROM `$nage` ORDER BY a_id DESC LIMIT 0, 1" ;
$run=mysqli_query($conn,$query);
$rowsCount=mysqli_num_rows($run);
$count = 0;
while($row=mysqli_fetch_array($run)) {
$count++;
$isFirst = ($count == 1) ? true : false;
$isLast = ($count == $rowsCount) ? true : false;
if (!$isLast) {
$page_title=$row['title'];
$img_src=$row['img_src'];
// $page_desc=$row['story'];
echo "<tr bgcolor='pink'>
<td style='width:40%'>
<div class='titleDivX'>
<img class='imgFrame'src='$img_src' alt='tasvir'/>
<h5> $page_title</h5>
</div>
</td>
<td bgcolor='yellow'>
<div class='titleDivX'> </div>
</td>
</tr>";
}
}
?>
Upvotes: 1