Reputation: 29
I am new to mysql and php and I am struggling with this issue. I am bulding a "blog-like" website just to learn the languages, and I came across this problem.
I want to display articles on the homepage, relevant to their "age". This means, the biggest slider should show the latest article, and two small articles below this should be the second and third latest article.
I would do it by ID but I am really stuck somewhere in the middle. I made this prototype code which works like I want, but I am 100% sure there is a simplier way + If I would like to spread 10 latest articles across the whole homepage, that would be just crazy to create each variable for each article.
I am open to any suggestions but please note, that I am still noob in PHP & MYSQL. Thank You.
<?php
require('connect.php');
$sql1 = mysqli_query($connect, "SELECT * FROM articles ORDER BY id DESC LIMIT 1");
$sql2 = mysqli_query($connect, "SELECT * FROM articles ORDER BY id DESC LIMIT 1,1");
$sql3 = mysqli_query($connect, "SELECT * FROM articles ORDER BY id DESC LIMIT 1,2");
$latestarticle = mysqli_fetch_array($sql1);
$secondlatestarticle = mysqli_fetch_array($sql2);
$thirdlatestarticle = mysqli_fetch_array($sql3);
?>
and this is the HTML part
<!--First Big Slide-->
<a href="#"><?=htmlspecialchars($firstlatestarticle['name'])?></a>
<!--Small Article below-->
<a href="#"><?=htmlspecialchars($secondlatestarticle['name'])?></a>
<!--Another Small Article below-->
<a href="#"><?=htmlspecialchars($thirdlatestarticle['name'])?></a>
Upvotes: 1
Views: 222
Reputation: 7911
You're pretty much on the right track here, but the implementation is a bit off.
if($result = mysqli_query($connect, "SELECT * FROM articles ORDER BY id DESC LIMIT 3") != false){
while ($row = mysqli_fetch_array($result)) {
$articles[] = $row;
}
}
echo $articles[0]['name'];
echo $articles[1]['name'];
echo $articles[2]['name'];
While you attempt to sort on id, which is ofcourse the latest added to the table it should actually be done with sorting by the date when the article was added. However it still works as you want it so its fine.
But the real optimization is in your 3 separate query's to the database as in my example it is just 1.
Upvotes: 1
Reputation: 1166
Try something like this: (untested)
$sql = mysqli_query($connect, "SELECT * FROM articles ORDER BY id DESC LIMIT 10");
while ($row = mysqli_fetch_array($sql))
{
echo '<a href="#">'.htmlspecialchars($row['name']).'</a>';
}
Upvotes: 0