for loop problems

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
Hey all, I'm pretty new to php so please keep that in mind when you
razz me. ;)

Anyway, I'm trying to make it so that 3 columns of links will show up
on a page so

link1 link2 link3
link4 link5 link6
link7 link8 link9


I've got this code for it, but I get an error message if the number of
links in the database isn't an integer divided by three. So if it's not
3,6,9,12, etc. I get

Warning: mysql_result(): Unable to jump to row 4 on MySQL result index
3 in mydirectory/loop.php on line 14

I'd like it to stop if there is a number not divisible by 3, but I'm
guessing it just keeps going.

here's the code.

for ($i = 0; $i < mysql_num_rows($result);)
         echo '<table align="center" cellpadding="0" cellspacing="0"
width="90%"> <tr>';
         for ($a = 0; $a < 3; $a++)
         $articlename = mysql_result($result, $i, "articlename");
         $articletitle = mysql_result($result, $i, "articletitle");
         echo '<td width="33%" align="center" valign="top"> <p><a
href="/articles/' . $articlename . '/articles.php">' . $articletitle
.'</a></p> </td>';
         echo '</tr></table><br>';

Thanks for your time.

Re: for loop problems

Try it this way:


$total = mysql_num_rows($result);
$width = 3;

$rows = ceil($total / $width);

$counter = 0;

echo '<table border=1>';
for ($y = 1; $y <= $rows; $y += 1)
    echo '<tr>';

    for ($x = 1; $x <= $width; $x += 1)
        $counter += 1;

        if ($counter <= $total)
            $articlename = mysql_result($result, $counter - 1, $articlename");
            $articletitle = mysql_result($result, $counter - 1, "articletitle");
            echo '<td>Link!</td>';
            echo '<td>&nbsp;</td>';

    echo '</tr>';

echo '</table>';


I tested the logic part but not the db stuff.  Good luck wrote:
Quoted text here. Click to load it

Re: for loop problems

There is a small bug with the quoting.  You'll spot it right away:

Should be:  $articlename = mysql_result($result, $counter - 1, "articlename");

Site Timeline