简体   繁体   中英

Populating table from database

I am trying to populate a table with the query results I receive from a function. I am able to populate the table however my table header keeps repeating in each row. Is the any way I can stop this from happening?

You need to put table header outside of your while loop:

echo '<table border="1" style="width:100%">';
           echo '<tr><td> Dep</td><td> Style</td> <td> Colour</td><td> Description</td> <td> Price</td></tr>';
        while($row = mysql_fetch_assoc($get5star)){

           echo'<tr><td> '.$row['departmentid']. '</td><td>'.$row['style']. '</td> <td> '.$row['colour']. '</td> <td> '.$row['description']. '</td> <td>'.$row['price'].'</td> </tr>';

           }
echo '</table>';

because your table's head part is inside of loop you should do like this for example we get book names and writer's name :

    <table>
<thead>
<th>book></th>
<th>writer</th>
</thead>
<tbody>
<?php 
while($row = mysql_fetch_assoc($get5star)){


           echo'
<tr><td> '.$row['book']. '</td><td>'.$row['writer']. '</td> </tr>
';

           }
?>
</tbody>
</table>

however my table header keeps repeating in each row

That's because it's inside the loop. The general structure of a loop is:

(stuff that happens once)
while (some condition) {
    (stuff that happens many times)
}
(stuff that happens once)

If the UI table header should happen only once (which it should), then it needs to go in one of those (stuff that happens once) locations. In this case, the first one:

// happens once
echo '<table border="1" style="width:100%">';
echo '<tr><td> Dep</td><td> Style</td> <td> Colour</td><td> Description</td> <td> Price</td></tr>';

while($row = mysql_fetch_assoc($get5star)){
    // happens many times
    echo'<tr><td> '.$row['departmentid']. '</td><td>'.$row['style']. '</td> <td> '.$row['colour']. '</td> <td> '.$row['description']. '</td> <td>'.$row['price'].'</td> </tr>';
}

// happens once
echo '</table>';

You have the table head code inside the loop:

while($row = mysql_fetch_assoc($get5star)){
   echo '<tr><td> Dep</td><td> Style</td> <td> Colour</td><td> Description</td> <td> Price</td></tr>';

You should put that outside the while loop, like this:

echo '<table border="1" style="width:100%">';
echo '<tr><td> Dep</td><td> Style</td> <td> Colour</td><td> Description</td> <td> Price</td></tr>';
   while($row = mysql_fetch_assoc($get5star)){
       echo'<tr><td> '.$row['departmentid']. '</td><td>'.$row['style']. '</td> <td> '.$row['colour']. '</td> <td> '.$row['description']. '</td> <td>'.$row['price'].'</td> </tr>';
           }
echo '</table>';

Worth noticing that you shouldnt use mysql , to access the Database. Use PDO ( i prefer them ) or mysqli .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM