1

I have 5 pictures stored in a folder and their links stored on the database. I want to put them in a table of three columns on each row.

<body>
<center>
<table border='1'>
<?php
$host="";
$username="";
$password="";
$db_name="fruits_db";
$tbl_name="fruits_tbl";
$connection=mysqli_connect("$host","$username","$password","$db_name");
if (mysqli_connect_errno())
{
    echo "The application has failed to connect to the mysql database server: " .mysqli_connect_error();
}
$result = mysqli_query($connection, "SELECT * FROM fruits_tbl")or die("Error: " . mysqli_error($connection));
$num_rows=mysqli_num_rows($result);
$rows =  $num_rows/3;

for($i=1; $i<=$rows ; $i++)
{
    echo "<tr>";
    for($j=1; $j<=3; $j++)
    {
        while($row = mysqli_fetch_array($result))
        {
            echo
            ("<td width='180px' height='200px'>"
             ."<div class = 'fruit_image'>"
             ."<img src='"
             .$row['fruit_image']
             ."'/>"
             ."</div>"
             ."<div class = 'fruit_title'>"
             .$row['fruit_name']
             ."</div>"
             ."</td>"
            );
        }
    }
    echo "</tr>";
}

mysqli_close($connection);
?>
</table>
</center>
</body>
</html>

The above code I created, contains two FOR loops. The script should count the number of rows in the table, and then divide by 3(the number of columns on each row in the HTML table). I wonder where I'm going wrong wit this code.

1
  • 1
    Your inner while() loop is doing to completely consume the DB results, so the 2nd and subsequent $j loops are going to have NO data to work with, because there's no results left from the query. Commented Jun 2, 2013 at 2:25

5 Answers 5

1

With your while($row = mysqli_fetch_array($result)){} inside your 1st for loop it will run through all your rows, before the outside loop runs 2nd/3rd time.

Here is another way to do it -

$counter = 1;
// start 1st row
echo "<tr>";
while($row = mysqli_fetch_array($result)){
// if the 4th cell, end last row, and start new row
    if ($counter%3==1){
        echo "</tr><tr>";
    }
    echo
        "<td width='180px' height='200px'>"
        ."<div class = 'fruit_image'>"
        ."<img src='"
        .$row['fruit_image']
        ."'/>"
        ."</div>"
        ."<div class = 'fruit_title'>"
        .$row['fruit_name']
        ."</div>"
        ."</td>";
    // increase the counter
    $counter++;
}
// close the last row
echo "</tr>";
Sign up to request clarification or add additional context in comments.

Comments

0

You're looping through all the results in the first table cell. Try something like this instead:

for($i=1; $i<=$rows ; $i++) {
    echo "<tr>";
    for($j=1; $j<=3; $j++) {
        $row = mysqli_fetch_array($result);
        if ($row) {
            echo(
                "<td width='180px' height='200px'>"
                ."<div class = 'fruit_image'>"
                ."<img src='"
                .$row['fruit_image']
                ."'/>"
                ."</div>"
                ."<div class = 'fruit_title'>"
                .$row['fruit_name']
                ."</div>"
                ."</td>"
            );
        }
    }
    echo "</tr>";
}

4 Comments

thanks a lot... It's working. I also had to change the $rows = $num_rows/3; to $rows = $num_rows%3;
That actually won't work for larger numbers. It should be $rows = ceil($num_rows / 3);
Thanks, so this should always round it up to the next highest integer value. Been looking for this...
By the way, is there a way in the loop I could load only 6 cells (3 columns per row) on each page, and have it pick up from where it left off in the previous page?... i.e, load all items from 1 - 6 rows on the database and then on the next page, load rows 7 - 12 and rows 13 - 18 on the next, etc...
0

If you just want to format the display with a new row after every 3 records, you could use the modulus operator:

$cntr = 0;
echo '<tr>';
while($row = mysqli_fetch_array($result)) {
   $cntr++;
   echo '
      <td width="180px" height="200px">
         <div class="fruit_image">
            <img src="'.$row['fruit_image'].'" />
         </div>
         <div class="fruit_title">'.$row['fruit_name'].'</div>
      </td>';
   if ($cntr % 3 == 0 && $cntr != $num_rows)
      echo '</tr><tr>';
}
echo '</tr>';

Keep in mind however that all the solutions presented so far may leave you with a last row with one or two td elements. You can fill this if you desire with empty <td>&nbsp;</td> columns.

2 Comments

thanks. I will try this code too. However I am not so much worried about the missing td elements as I won't be using that area. But for the sake of pure html principle, maybe I should be worried...?
As long as the display is ok, it doesn't really matter.
0
    print "<center><table border=1>
        <tr>
        <td>id</td>
        <td>name</td>
        <td>company</td>
        <td>branch</td>
        <td>job title</td>
        <td>contact</td>
        <td>email</td>
        <td>mgs</td>
        </tr>";

    while($row=mysql_fetch_array($query))
    {
        print "<tr>";
       for ($i=0;$i<=(count($row)/2);$i++)
              {
               print "<td>$row[$i]</td>";
               } print"</tr>";
   }

    }
    else{echo " <p>No Records Found</p>";}

1 Comment

How to fetch and print table with minimum line of code this code. it can be use in function and in class also.
0
<?php
function studentTable($name,$grade){
echo "<tr> <td>$name</td><td>$grade</td></tr>";
}
?>
    <table style="width:100%" border="solid">
<tr>
<th>Name</th>
<th>Grade</th> 
 </tr>
 <?php studentTable("Sarah", 90) ?>

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.