MySQL Help Needed - How to Select the Most Recent Row

Hey, the title is basically saying it all.

I have a comment script, but there is one problem. I need to select the most recent row. It’s always showing row 1, but if it has to echo 2 rows, it just echoes the first row twice.

BASIC RUNDOWN

How do I select the most recent MySQL row?

Thanks in advance

Assuming you’re using an auto_increment field such as id

SELECT `field`,`another_field` FROM `mytable` ORDER BY `id` DESC LIMIT 1

It’s still strangely not working. Is there a way of inserting it in descending order?

No, its not possible to tell it the order to insert, however, what you can do is use mysql_insert_id() to get the last record. its important to put that right after the insert though, else it won’t work. once you have the id, use it to query for it.

I don’t mean this to sound rude, but that SQL query works (providing you still require the most recently inserted row, and are using an auto incremental field called id). The issue may well be lying in your PHP and how it is dealing with the result - would you mind posting the PHP side of things so that we may rule that out as an issue.

I’ve taken out the code that you said, Smokey, because it didn’t work.

[php]

Comments

Enter your comment! <?php $oneone = "SELECT * FROM feeds WHERE profile='$email' ORDER BY 'commentUID' DESC"; $twotwo = mysql_query($oneone); $rowrow = mysql_fetch_row($twotwo);

$poster = $rowrow[1];
$feed = $rowrow[2];
$commentid = $rowrow[3];
$commentUID = $rowrow[4];

$banana = mysql_num_rows($twotwo);
if($banana == 0) {
echo “No comments. Be the first to comment?”;
}
else {
while($banana > 0) {
echo “<a href=“profile.php?personID=$commentid”>” . $poster . “” . "

" . $feed . "



";
$banana = $banana - 1;
}
}
?>[/php]

Don’t ask why I did $banana.

The problem I’m getting is when I echo them out, it just echos the first comment the same number of times.

Say that there are 5 different comments, they would all look like this.

X. Ample
First comment!

X. Ample
First comment!

X. Ample
First comment!

X. Ample
First comment!

X. Ample
First comment!

Can I organize them by dates?

It’s because you’re only getting one row from your results.

Your code needs to reflect this layout:
[php]$sql = “SELECT * FROM table”;
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0)
{
while(false !== ($row = mysql_fetch_assoc($result)) //Does whatever’s in the loop for every row in the query’s results
{
echo $row[‘field1’];
}
}[/php]

Sponsor our Newsletter | Privacy Policy | Terms of Service