after each 5 results? This is my code: $query = mysql_query("SELECT * FROM books ORDER BY id") or die(mysql_error()); while(...">

How to insert <br/"> after each 5 results?

This is my code:

$query = mysql_query("SELECT * FROM books ORDER BY id") or die(mysql_error()); while($row = mysql_fetch_assoc($query)) { echo $row["bookname"]." - "; } 

How to make only 5 books displayed on each line by inserting
at the beginning, if line 5 or 10 or 15, etc ...

thanks

+4
source share
5 answers

You can count the number of cycles that you looped (increase the value of the variable each time).

Compare the absolute value of 5. If the result is 0, print <

 $rowCounter = 1; while($row = mysql_fetch_assoc($query)) { echo $row["bookname"]." - "; if( $rowCounter % 5 == 0 ) { echo "<hr />"; } $rowCounter++; } 
+7
source

A simple way would be to increment the counter ... and check its mod (%) for 5.

So

 if (i % 5 == 0) echo $row["bookname"]; 
+2
source
 $query = mysql_query("SELECT * FROM books ORDER BY id") or die(mysql_error()); $counter=1; while($row = mysql_fetch_assoc($query)) { echo $row["bookname"]." - "; if($counter%5==0){echo "<br/>";} $counter++; } 
+1
source

Optimized version of michaels code! :)

 $rowCounter = 0; $possibleHR = array("","","","","<hr/>"); while($row = mysql_fetch_assoc($query)) { echo $row["bookname"]." - ".$possibleHR[($rowCounter++) % 5]; } 
+1
source

A shorter version of Michael's code:

 $rowCounter = 0; while ($row = mysql_fetch_assoc($query)) { echo $row["bookname"] . ' - '; if (++$rowCounter % 5 == 0) { echo '<br />'; } } 

Another alternative:

 $rowCounter = 1; // not sure if this should be 1 or 0 // 1 is correct, check comments while ($row = mysql_fetch_assoc($query)) { echo $row["bookname"] . ' - '; if ($rowCounter++ % 5 == 0) { echo '<br />'; } } 
0
source

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


All Articles