0

Let's say I have a user that entered 12 links into the database but when they are displayed I want to break up the links into groups of 3 and repeat the groups of three until all 12 kinks are displayed for example.

<div>
    <p><a href="">Link 1</a></p>
    <p><a href="">Link 2</a></p>
    <p><a href="">Link 3</a></p>
</div>

Here is part of the code I'm working with. How should my code look like?

while ($row = mysqli_fetch_assoc($dbc)) {
        if (!empty($row['category']) && !empty($row['url'])) {
                echo '<div>';
                echo '<p><a href="' . $row['url'] . '" title="' . $row['category'] . ' Category Link">' . $row['category'] . '</a></p>';
                echo '</div>';
    }

}

3 Answers 3

1

Something like this gets you three links per div. We add the extra conditional echo at the end for the case that there's not a multiple of 3 links

$ctr = 0;
while ($row = mysqli_fetch_assoc($dbc)) {
    if (!empty($row['category']) && !empty($row['url'])) {
        if ($ctr%3 == 0) {
            echo '<div>';
        }
        $ctr ++;
        echo '<p><a href="' . $row['url'] . '" title="' . $row['category'] . ' Category Link">' . $row['category'] . '</a></p?';
        if ($ctr%3 == 0) { 
            echo '</div>';
        }
    }

}
if ($ctr%3 != 0) { 
  echo '</div>';
}
Sign up to request clarification or add additional context in comments.

Comments

0

if you want to avoid incrementing/resetting i every time you reach three, you can just use the modulus operator:

http://php.net/manual/en/language.operators.arithmetic.php

Something like:

if( $i%3 == 0 ){
  // divisible by 3...
}

Comments

0

An easier method would be more like:

while(true) {
    $c = 0;
    echo "<div>";
    while ($row = mysqli_fetch_assoc($dbc) && $c++ < 3) {
        if (!empty($row['category']) && !empty($row['url'])) {
            echo '<p><a href="' . $row['url'] . '" title="' . $row['category'] . ' Category Link">' . $row['category'] . '</a></p>';
        }
    }
    echo "</div>";
    if(empty($row))
        break;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.