a4aLien
a4aLien

Reputation: 25

Pagination of PHP echoed Content

PHP is an alien language for me. I am trying to pull some fields from WP's SQL database.. The content comes out okay but is a lot. I want to somehow put it in a HTML carousel or some slider, where data must be formatted like this:

<holder1>
  <data1></data1>
  <data2></data2>
  <data3></data3>
</holder1>
<holder2>
  <data4></data4>
  <data5></data5>
  <data6></data6>
</holder2>

I imagine I would have to put some for loop for i<4, do, then break into holder2.

Current script that echos the data =

while($row = mysql_fetch_array($rs)) {

echo "<div class='testimonials flexslider'><ul class='slides'><li class='testimonial flex-active-slide'><blockquote><p>" . $row['post_content'] . "</p><cite><span>" . $row['post_title'] . "</cite></span></blockquote></li></ul></div>"; }

I would like it to break after 3 <li> items each, into a seperate <div> or <article> whatever I find suitable according to the carousel I use.

Upvotes: 0

Views: 50

Answers (1)

Glorfindel
Glorfindel

Reputation: 22641

You need an index variable, which echoes the beginning of the wrapper when it is divisible by 3, and the end of the wrapper when it leaves a remainder of 2 after division by 3 (and at the very end). It seems like this code would work:

$index = 0;
while($row = mysql_fetch_array($rs)) {
    if ($index % 3 == 0) {
        echo "<div class='testimonials flexslider'><ul class='slides'>";
    }

    echo "<li class='testimonial flex-active-slide'><blockquote><p>" . $row['post_content'] . "</p><cite><span>" . $row['post_title'] . "</cite></span></blockquote></li>";

    if ($index % 3 == 2) {
        echo "</ul></div>";
    }
    $index++;
}
if ($index % 3 != 2) {
    echo "</ul></div>";
}

EDIT: a little bit of explanation to clarify the math. Suppose you have 10 results. Because we usually count from 0 in programming, they can be numbered 0 up to 9. This would make your structure look like this:

<holder>
  <data0></data0>
  <data1></data1>
  <data2></data2>
</holder>
<holder>
  <data3></data3>
  <data4></data4>
  <data5></data5>
</holder>
<holder>
  <data6></data6>
  <data7></data7>
  <data8></data8>
</holder>
<holder>
  <data9></data9>
</holder>

You see that we need a <holder> before elements 0, 3, 6 and 9 - all numbers which are divisible by 3. Mathematically, this is expressed with help of the remainder function - a number is divisible by 3 when its remainder after dividing by 3 is zero.

Likewise, we need a </holder> after elements 2, 5 and 8 - numbers which after division by 3 leave a remainder of 2.

We need to take care of the situation where the last block is not complete; that's why there's an extra block of code to take care of the last </holder>.

Upvotes: 2

Related Questions