views:

179

answers:

4

I have a movie database Kind of like a blog and I want to display the last 4 created entries. I have a column in my table for timestamp called 'dateadded'. Using this code how would I only display the 4 most recent entries to table

<?php
//connect to database
mysql_connect($mysql_hostname,$mysql_user,$mysql_password);
@mysql_select_db($mysql_database) or die("<b>Unable to connect to specified database</b>");
//query databae
$query = "SELECT * FROM movielist";
$result=mysql_query($query) or die('Error, insert query failed');
$row=0;
$numrows=mysql_num_rows($result);

while($row<$numrows)
{
$id=mysql_result($result,$row,"id");
$imgurl=mysql_result($result,$row,"imgurl");
$imdburl=mysql_result($result,$row,"imdburl"); ?>

  <div class="moviebox rounded"><a href="http://&lt;?php echo $domain; ?>/viewmovie?movieid=<?php echo $id; ?>" rel="facebox">
            <img src="<?php echo $imgurl; ?>" />
            <form method="get" action="">
   <input type="text" name="link" class="link" style="display:none" value="http://us.imdb.com/Title?&lt;?php echo $imdburl; ?>"/>
 </form>
    </a></div>

<?php

$row++;
}
?>
+4  A: 

$query = "SELECT * FROM movielist ORDER BY dateadded DESC LIMIT 4";

Ordering by dateadded in descending order gives you the most recent entries on top, then you can take only the 4 most recent ones by issuing LIMIT 4.

Tatu Ulmanen
A: 

Use this query:

SELECT * FROM movielist ORDER BY dateadded DESC LIMIT 4
Justin Ethier
A: 

Assuming you're using MySQL:

SELECT * FROM 'movielist' ORDER BY 'dateadded' DESC LIMIT 4;
XpiritO
A: 

While the five already submitted answers will work, you should select as little as you need to from your table - so if you were to add extra fields in later it would not select them. Therefore:

SELECT `id`, `imgurl`, `imdburl` FROM movielist ORDER BY dateadded DESC LIMIT 4

would be better for performance reasons - you are only selecting the fields which you are actually using.

Thomas McDonald