Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.