title: Splitting MySQL results into 3 columns with PHP
body: <p>I'm trying to output results from my database into 3 columns (varying numbers of records) but not having any success. I've found a few solutions (<a href="https://stackoverflow.com/questions/8660484/spliting-php-mysql-data-into-3-columns">this</a> being the closest) but most of them work horizontally with table markup, whereas my markup is already columns.</p>
  
  <p>Code structure as follows:</p>
  
  <pre><code>&lt;div class="grid"&gt;
      &lt;div class="col"&gt;
          result 1
          result 2
          result 3
      &lt;/div&gt;
      &lt;div class="col"&gt;
          result 4
          result 5
          result 6
      &lt;/div&gt;
      &lt;div class="col"&gt;
          result 7
          result 8
          result 9
      &lt;/div&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>My current PHP attempt is as follows:</p>
  
  <pre><code>echo "&lt;div class='col'&gt;";
  
  $result = $mysqli-&gt;query("SELECT * FROM stories ORDER BY RAND()");
  $resultCount = $result-&gt;num_rows;
  $i = 0;
  while($row = $result-&gt;fetch_assoc())
  {
  
  if($i &gt; 0 AND $i % 3 == 0) {
  echo "&lt;/div&gt;&lt;div class='col'&gt;";
  }
  
  ?&gt;
    &lt;div class="result"&gt;
        content here
    &lt;/div&gt;
  &lt;?php
  $i++;
  }
  
  echo "&lt;/div&gt;";
  </code></pre>
  
  <p>This works with my example of 9 results, but as soon as there's 10 it creates a 4th column which breaks the layout. I can see why, as I'm telling it to end and start a new column every 3 results without stopping. </p>
  
  <p>I know I need to be doing something with the total number of records and splitting that into 3, but that's where I'm stuck. If there's a remainder (e.g. 10) I guess I'd prefer it sits in the first column, so the results set would be split into 4/3/3.</p>
  
  <p>Ideas/suggestions much appreciated!</p>
  
  <p><em>Note: I had considered it would be easier to do this with a different HTML structure, but due to the layout it needs to be vertically in columns as the individual results are varying height boxes that can expand/contract, so structurally it needs to stay like this.</em></p>