neogemima Posted May 5, 2009 Share Posted May 5, 2009 Hello. I have a table that holds posts from my users. I am trying to display the thirty most recent posts from my users using php. Seemed simple for me, but I am new to php. The method I used was to assign each row a unique id and use the function mysqli_num_rows to return a number and then use that number in a for loop to display the rows limiting my results to 30. My problem arises when I delete a row. The ids no longer match up to the row number because I've deleted one somewhere. How can I overcome this and still display the thirty most recent posts. Here is my code that no longer works: $num_rows = mysqli_num_rows($result); $i = $num_rows; for($i = $num_rows; $i >= ($num_rows - 30); $i--) { $sql = "SELECT id, date, title FROM Newsposting WHERE id = $i"; $queryresult = mysqli_query($db, $sql); $rowresult = mysqli_fetch_array($queryresult, MYSQLI_ASSOC); $id = $rowresult['id']; echo '<a href="article.php?id='.$id.'">'.$rowresult['date'].' '.$rowresult['title'].'</a>'; echo "<br>"; } I've searched and can't figure out how to specify in my query the last thirty rows in the table and to order them by most recent to oldest. Any help appreciated. Thanks. Quote Link to comment https://forums.phpfreaks.com/topic/156990-solved-return-most-recent-posts-rows-from-table/ Share on other sites More sharing options...
Maq Posted May 5, 2009 Share Posted May 5, 2009 Let MySQL handle that for you. You can order the ids by descending and limit them by 30. Something like: $sql = "SELECT id, date, title FROM Newsposting ORDER BY id DESC LIMIT 30"; $queryresult = mysqli_query($db, $sql); while($rowresult = mysqli_fetch_array($queryresult, MYSQLI_ASSOC)) { $id = $rowresult['id']; echo ''.$rowresult['date'].' '.$rowresult['title'].''; echo " "; } Quote Link to comment https://forums.phpfreaks.com/topic/156990-solved-return-most-recent-posts-rows-from-table/#findComment-827003 Share on other sites More sharing options...
neogemima Posted May 5, 2009 Author Share Posted May 5, 2009 That's perfect, thank you very much. I knew it was going to be simple. Quote Link to comment https://forums.phpfreaks.com/topic/156990-solved-return-most-recent-posts-rows-from-table/#findComment-827021 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.