How grouping data with php and display it inside table (table in table)?

581

I have problem when grouping data table in table. I've made ​​but I think the results are not in accordance with the expected.

This is the example script :

<?php

$conn=mysql_connect('localhost','root',''); 
mysql_select_db('things',$conn) or die ("Database Not Found"); 
$result = mysql_query("SELECT id, name, size, color FROM things ORDER BY color");  
$state = -1;
$no = 1;    

echo '<table border=1><tr><td>INDEX OF COLOR</td></tr><tr><td>';

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

        if($state!= $row['color']) {
            $no = 1;
            echo '<tr bgcolor=yellow><td>'.$row['color']."</td></tr>";
            echo '<tr><td><table border=1><tr><th>no</th><th>NAME OF HERO</th></tr>';
            $state = $row['color'];
        }

        echo '<tr><td>'.$no.'</td><td>'.$row['name'].'</td></tr>';




        $no++;

    } 

    echo '</td></tr></table>';  

?>

That code produces the wrong table in the table. The desired outcome is the Color Group>> Details (Table).

I need result like this :)

+

can anyone help me, why this code wrong? Thank you. :)

598

Answer

---------+ | INDEX OF COLOR | +
230

Answer

---------+ |RED | +
963

Answer

---------+ | +
5

Answer

+ | | |HERO | | | +
992

Answer

+ | | |ROBIN | | | +
736

Answer

+ | | |INCREDIBLE| | | +
79

Answer

+ | +
16

Answer

---------+ |BLUE | +
478

Answer

---------+ | +
318

Answer

+ | | |HERO | | | +
419

Answer

+ | | |SPIDEY | | | +
660

Answer

+ | | |SUPER MAN | | | +
962

Answer

+ | | |ICE MAN | | | +
47

Answer

+ | +
494

Answer

---------+
409

Answer

Solution:

I think your table is way more complex than it needs to be. I haven't tested this, but try it out.

$first_color = true;
echo '<table border=1><tr><td>INDEX OF COLOR</td></tr>';

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

    if($state!= $row['color']) {
        if(!$first_color) {
            echo '</table></td></tr>';
            $first_color = true;
        }
        $no = 1;
        echo '<tr bgcolor=yellow><td>'.$row['color']."</td></tr>";
        echo '<tr><td><table border=1><tr><td>no</td><td>NAME OF HERO</td></tr>';
        $state = $row['color'];
    }

    echo '<tr><td>'.$no.'</td><td>'.$row['name'].'</td></tr>';




    $no++;

} 

echo '</table></td></tr></table>';

People are also looking for solutions to the problem: php - How to store page url to mysql database

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.