I am trying to output each row from a mysql query slightly differently in terms of styling, however I want to try to avoid having to use offsets and multiple queries.
Current code:
$sql = "SELECT * FROM news ORDER BY id DESC LIMIT 1";
$query = mysqli_query($connection, $sql);
while($row = mysqli_fetch_array($query)){
$title = $row["title"];
// output first news item with a style
echo '<div class="style-1">'.$title.'</div>';
}
$sql = "SELECT * FROM news ORDER BY id DESC LIMIT 1 OFFSET 1";
$query = mysqli_query($connection, $sql);
while($row = mysqli_fetch_array($query)){
$title = $row["title"];
// output second news item with different style
echo '<div class="style-2">'.$title.'</div>';
}
I would thus like to avoid having 2 (or more) queries simple because I want to use different css classes for each while row, something like this:
$sql = "SELECT * FROM news ORDER BY id DESC LIMIT 10";
$query = mysqli_query($connection, $sql);
while($row = mysqli_fetch_array($query)){
$title = $row["title"];
} // end while
$i = 1;
for($i; $i<2; $i++){ // output first row item with first style
echo '<div class="style-1">'.$title.'</div>';
} // end for loop 1
for($i; $i<3; $i++){ // output first row item with second style
echo '<div class="style-2">'.$title.'</div>';
} // end for loop 2
for($i; $i<4; $i++){ // output third row item with third style
echo '<div class="style-3">'.$title.'</div>';
} // end for loop 3
...
Desired Output:
<div class="style-1">News Headline Title 1</div>
<div class="style-2">News Headline Title 2</div>
<div class="style-3">News Headline Title 3</div>
...
I'm assuming you want 3 different styles, and here's how I would accomplish this:
$sql = "SELECT * FROM news ORDER BY id DESC LIMIT 10";
$query = mysqli_query($connection, $sql);
$i = 1;
while($row = mysqli_fetch_array($query)){
$title = $row["title"];
if($i<2){
$styleNumber = 1;
}
else if($i<3){
$styleNumber = 2;
}
else if($i<4){
$styleNumber = 3;
}
echo '<div class="style-'.$styleNumber.'">'.$title.'</div>';
$i++;
}
// end while
Output :
Title 1 (Style 1)
Title 2 (Style 2)
Title 3 (Style 3)
Title 4 (Style 3)
This is not an answer. Just a comment/improvement of @JonTan answer since it was chosen as correct one.
My guess is that OP need to loop styles for every 3 records, but not to set style only for 3 first returned.
That means we can change condition from if($i<3){
, if($i<2){
to something like:
$i = 1;
while($row = mysqli_fetch_array($query)){
$title = $row["title"];
if($i % 3 == 0){
$styleNumber = 3;
} else if($i % 2 == 0){
$styleNumber = 2;
} else {
$styleNumber = 1;
}
echo '<div class="style-'.$styleNumber.'">'.$title.'</div>';
$i++;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.