PHP: display records from a database in groups of five?

Is it possible, and if so, how to do this, to select all the records in the table in my database, and then display five results at a time in one group.

Meaning: an example is that I have 15 records in a common database, then I want to present my data as follows:

<div class="1-5">Record[1], Record[2], Record[3], Record[4], Record[5]</div>

<div class="6-10">Record[6], Record[7], Record[8], Record[9], Record[10]</div>

<div class="11-15">Record[11], Record[12], Record[13], Record[14], Record[15]</div>

I'm not quite sure if I can do this with an SQL statement or do I need to write some kind of "do ... while" or loop to retrieve each data set. I also thought about something with arrays, but did not get the result.

thanks

  • Mestika
+3
source share
2 answers

array_chunk(), .

// pull all the records into an array
$query = mysql_query('SELECT * FROM mytable');
$rows = array();
while ($row = mysql_fetch_array($query)) {
  $rows[] = $row;
}

// this turns an array into an array of arrays where each sub-array is
// 5 entries from the original
$groups = array_chunk($rows, 5);

// process each group one after the other
$start = 1;
foreach ($groups as $group) {
  $end = $start + 4;

  // $group is a group of 5 rows. process as required
  $content = implode(', ', $group);

  echo <<<END
<div class="$start-$end">$content</div>

END;
  $start += 5;
}

, , , , , , , , (), .

+4

, , 5:


$i =1;    
while ($row = mysql_fetch_array($query)) {
 echo $row['name']."\n";
 if ($i % 5 == 0)
 {
   echo 'hr'; // Or any other separator you want
 }
 $i++;
}
+1

Source: https://habr.com/ru/post/1723971/


All Articles