Johnny Johnny - 7 months ago 27
SQL Question

PHP: split a mySQLi array in two divs?

I'm currently working on a page that calls a mySQL database to populate a list of members. However, I need that list to be split into two equal parts, so that half can float to the left and half to the right. However, I have beat this horse to death and still cannot figure out how to split the array.

Here's what I have currently:

<div class="holder">
<?php
$members = $db->query('SELECT * FROM tableContacts ORDER BY lastName ASC');
$rowcount = mysqli_num_rows($members);
if ( $rowcount > 0 ) { ?>
<div class="members-left">
<ul class="members">
<?php while ($row = $members->fetch_assoc()) { ?>
<li class="member">
//SOME CONTENT HERE
</li>
<?php } ?>
</ul>
</div>
<?php } ?>
</div>


However, I want the output to look something like this (let's say my table has 10 members):

<div class="holder">
<!--output first half of members from table: -->
<div class="members-left">
<ul class="members">
<li class="member">...</li>
<li class="member">...</li>
<li class="member">...</li>
<li class="member">...</li>
<li class="member">...</li>
</ul>
</div>

<!--output second half of members from table: -->
<div class="members-right">
<ul class="members">
<li class="member">...</li>
<li class="member">...</li>
<li class="member">...</li>
<li class="member">...</li>
<li class="member">...</li>
</ul>
</div>

</div>


I've tried setting counters and using things like
if($i <= $rowcount/2)
, but to no avail. Any help would be greatly appreciated—I'm very new to mySQL and have limited knowledge of PHP, so this one has me stumped.

Answer

add a control variable like "$i". add +1 to $i every loop. and check if $i reached half of number of rows. if reached close ul and div and open new div and ul and set $i to 0

  <div class="holder">
    <?php
    $members = $db->query('SELECT * FROM tableContacts ORDER BY lastName ASC');
    $rowcount = mysqli_num_rows($members);
    $i=0;
    if ( $rowcount > 0 ) { ?>
        <div class="members-right">
            <ul class="members">
                <?php while ($row = $members->fetch_assoc()) { ?>
                    <li class="member">
                        //SOME CONTENT HERE
                    </li>
                <?php
                $i++;
                 if($i>=($rowcount/2)){
                 echo '</ul></div>
<div class="members-right">
        <ul class="members">'; 
$i=0;
                    }

                   } ?>
            </ul>
        </div>
    <?php } ?>
</div>
Comments