开发者

Latest 5 images from each category displayed in a summary

I have 2 tables in My database and I wanted a PHP output of the following, how can I do this?

Latest 5 Catname1 Images

image42.jpg, image45.jpg ect ect

Latest 5 Catname2 Images

image41.jpg, image44.jpg ect ect

Latest 5 Catname3 Images

image43.jpg, image46.jpg ect ect

I have 2 tables in mysqly layed out like this:

imagedb (MySql Table name)

iid,iname,icat,idesc,itags,ithumb

41,Name41,2,desc41,tag41,image41.jpg

42,Name42,1,desc42,tag42,image42.jpg

43,Name43,3,desc43,tag43,image43.jpg

44,Name44,1,desc44,tag44,image44.jpg

45,Name45,2,desc45,tag45,image45.jpg

46,Name46,3,desc46,tag46,image46.jpg

Ect ect

categories (MySql Table name)

cid,c开发者_如何转开发name,cdesc,ctags

1,catname1,catdesc1,cattags1

2,catname2,catdesc2,cattags2

3,catname3,catdesc3,cattags3

Hope this makes sense. Thank you...


The simplest thing to do would be to create a loop in PHP that fetches the last 5 images from the imagedb table based on each category you want to use.

$categories = mysql_query("SELECT cid, cname FROM categories");
while($row = mysql_fetch_assoc($categories)){
    echo "<strong>Latest 5 " . $row['cname'] . " Images</strong>";
    $image_query = mysql_query("SELECT * FROM imagedb WHERE cid = " . $row['cid'] . " ORDER BY iid DESC LIMIT 5;");
    $images = array();
    while($image = mysql_fetch_assoc($image_query))
        $images[]  = $image['iname']; // change this to $image['ithumb'] etc for different fields

    echo '<p>' . implode(', ', $images) . '</p>';
}

That will print pretty closely what you have entered there, (assuming the ID of each image indicates when it was inserted (higher means newer).

There are probably cleaner ways of doing this, and depending on your implementation you might need to loop once to get the data then again to print it, however this should give you a good headstart.


SELECT i.*
FROM categories c, imagedb i
WHERE c.cid = i.icat
GROUP BY categories.cid
ORDER BY i.iid DESC
LIMIT 5

Php code must be something like

$conn = mysql_connect("host", "user", "password");
mysql_select_db("db", $conn);

$query = mysql_query("[query above]");
$counter = 0;
while ($result = mysql_fetch_assoc($query))
{
    $results[$counter][] = $result;
    if (isset($results[$counter][4]))
    {
        $counter++;
        $results[$counter] = array();
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜