Jump to content

[SOLVED] Return most recent posts (rows) from table


neogemima

Recommended Posts

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.

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 "
";
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.