Reputation: 5
I have a database, i need to extract from them four record at a time.
To extract all the records i use this query:
SELECT image FROM song ORDER BY date DESC
but i need to process 4 record at a time, because in HTML i close a row every 4 images.
echo"<div class='row'>";
while ($dati=mysqli_fetch_assoc($result))
{
echo"<a href='song.php'>";
echo"<div class='col-md-3'>";
echo"<img class='img-responsive' src='".$dati['immagine']."'><br>";
echo"</div>";
echo"</a>";
}
echo "</div><br>";
I need to re-execute the command above every 4 image record as long as there are records not processed in the database.
Upvotes: 0
Views: 86
Reputation: 111
This will display four images in every row in your html using bootstrap after executing SELECT image FROM song ORDER BY date DESC
.
$num_rows = mysqli_num_rows($result);
for ($j = 0; $j < $num_rows; ++$j)
$dati[$j] = mysqli_fetch_assoc($result); //$dati is now a multidimensional array with an indexed array of rows, each containing an associative array of the columns
// You could alternatively use a for loop
// for($i=0; $i<$num_rows; $i++) insert while loop
$i=0;
while($i<$num_rows){ // start the loop to insert images in every row, 4 images per row
echo"<div class='row'>";
echo"<a href='song.php'>";
echo"<div class='col-md-3'>";
if($i<num_rows) // this prevents excessive rows from being displayed after $i reaches the number of rows
echo"<img class='img-responsive' src='".$dati[$i++]['immagine']."'><br>"; //post-increment $i
if($i<num_rows)
echo"<img class='img-responsive' src='".$dati[$i++]['immagine']."'><br>";
if($i<num_rows)
echo"<img class='img-responsive' src='".$dati[$i++]['immagine']."'><br>";
if($i<num_rows)
echo"<img class='img-responsive' src='".$dati[$i++]['immagine']."'><br>";
echo"</div>";
echo"</a>";
echo "</div><br>"
}
Upvotes: 0
Reputation: 913
Use Module of 4 and display your format
<?php
$counter=0;
$str="";
while ($dati=mysqli_fetch_assoc($result))
{
if($counter%4==0)
{
$str="<div class='row'>";
}
$str.="<a href='song.php'>";
$str.="<div class='col-md-3'>";
$str.="<img class='img-responsive' src='".$dati['immagine']."'><br>";
$str.="</div>";
$str.="</a>";
if($counter%4==0)
{
$str.="</div><br>";
}
$counter++;
}
echo $str;
?>
or if you dont want store into string directly print like this
<?php
$counter=0;
while ($dati=mysqli_fetch_assoc($result))
{
if($counter%4==0)
{
echo "<div class='row'>";
}
echo "<a href='song.php'>";
echo "<div class='col-md-3'>";
echo "<img class='img-responsive' src='".$dati['immagine']."'><br>";
echo "</div>";
echo "</a>";
if($counter%4==0)
{
echo "</div><br>";
}
$counter++;
}
?>
Upvotes: 0
Reputation: 4637
Use this query
SELECT image FROM song ORDER BY date DESC limit 4
Upvotes: 0
Reputation: 2166
LIMIT 4
but I would recommand you to query the record once and to add a counter in your loop to know when you have a new row
Upvotes: 1