How to make a cycle through php and mysql? How to add echo '<div>Реклама</div>'; after 2 entry and repeated every time? For example:

 1 2 echo '<div>Реклама</div>'; 3 4 echo '<div>Реклама</div>'; 5 6 echo '<div>Реклама</div>'; и т.д. 

Sample code

 <?php $query="SELECT * FROM table"; $result = mysql_query($query); $post = mysql_num_rows($result); while ($row = mysql_fetch_assoc($result)) { // Цикл } ?> 

enter image description here

  • What do you think the combination of while letters in your code means? - VladD
  • Are you unable to insert the word output before } in the loop? PS The mysql_ functions mysql_ outdated ! Remove them from your code forever. - Visman
  • @KYRAN so what prevents to write instead of $post_id = $row['post_id']; echo $post_id; $post_id = $row['post_id']; echo $post_id; just echo $row['post_id'].'<br />'; ??? Adding "words" at the end - Alexey Shimansky

2 answers 2

With your code it will be something like this:

it if you replace every third

 <?php $query="SELECT * FROM table"; $result = mysql_query($query); $i = 1; while ($row = mysql_fetch_assoc($result)) { if ($i % 3 == 0) echo '<div>Реклама</div>'; else echo 'Что-то там из массива'; ++$i } ?> 

That is, logically, if you argue, you need to insert advertising in every third block. Accordingly, in the cycle you look at the counter. If the counter turns out to be divided by 3 without a remainder, then we display the advertisement, and if not, then the rest.

If you want to add after each second, as in the example .. then you need to check the remainder of the division by 2

 <?php $query="SELECT * FROM table"; $result = mysql_query($query); $i = 1; while ($row = mysql_fetch_assoc($result)) { echo 'Что-то там из массива'; if ($i % 2 == 0) echo '<div>Реклама</div>'; ++$i } ?> 
  • Thanks, it works, but it replaces every 3 запись with an реклама but how can you do it so that you don’t just replace it afterwards? - KYRAN
  • @KYRAN corrected the answer. In that case, if you want to display content after each advertisement, then just the conditions of else should not be - Alexey Shimansky

If I understand you correctly,

 $select = $db->prepare("SELECT * FROM table"); // $db - PDO $select->execute(); $rows = $select->fetchAll(); $i = 1; foreach($rows as $row) { echo 'вывод из базы'; if($i % 3 == 0) echo '<div>Реклама</div>'; $i++; } 
  • Click the edit button in your post and describe your question in more detail. - mix
  • @KYRAN and I answer - mix