Benion
Benion

Reputation: 80

How can i merge Rows of An HTML table fetched from Mysql

I have a MySQL database for a website am building, i have displayed contents of a table in the MySQL database on my page using the PHP code shown below. What i wanted to know was if there was a way to Merge rows of a column with the same value.

note: i don't want the changes to occur in the database but just on the html table displayed on the page
here is the code i used

$arr = array();
while($row = mysql_fetch_row($result)) {
    if (empty($arr[$row[0]])) $arr[$row[0]] = array();
    $arr[$row[0]] [$row[1]] [$row[2]] [$row[3]] [$row[4]] [$row[5]] [$row[6]][] = $row[7];

}
foreach ($arr as $key => $subordinatearr) {
    echo '<tr>';
    echo '<td rowspan="', count($subordinatearr), '">', $key, '</td>';
    echo '<td>', $subordinatearr[0], '</td>';
    echo '<td>', $subordinatearr[1], '</td>';
    echo '<td>', $subordinatearr[2], '</td>';
    echo '<td>', $subordinatearr[3], '</td>';
    echo '<td>', $subordinatearr[4], '</td>';
    echo '<td>', $subordinatearr[5], '</td>';
    echo '<td>', $subordinatearr[6], '</td>';

    if (count($subordinatearr) > 1) {
        for ($i = 1; $i < count($subordinatearr); $i++) {
            echo '</tr><tr><td>', $subordinatearr[$i], '</td>';
        }
    }
    echo '</tr>';
}

Upvotes: 0

Views: 2619

Answers (3)

k.abbey
k.abbey

Reputation: 96

Store the result in an array.

$arr = array();
while($row = mysql_fetch_row($result)) {
    if (empty($arr[$row[0]]) $arr[$row[0]] = array();
    $arr[$row[0]][] = $row[1]; 
}

Then put the array using rowspan like as follows:

foreach ($arr as $key => $subordinatearr) {
    echo '<tr>';
    echo '<td rowspan="', count($subordinatearr), '">', $key, '</td>';
    echo '<td>', $subordinatearr[0], '</td>';
    if (count($subordinatearr) > 1) {
        for ($i = 1; $i < count($subordinatearr); $i++) {
            echo '</tr><tr><td>', $subordinatearr[$i], '</td>';
        }
    }
    echo '</tr>';
}

If data is too big, this may cause an memory error.

Upvotes: 0

Anirban Ghosh
Anirban Ghosh

Reputation: 74

I did not understand this part clearly - "Merge rows of a column with the same value." If you don't want to show duplicate records of a column, you can do it in two ways -

Option 1

Keep the value of specific column in an array. Before displaying that column check if the value exists in the array using is_array(). If exists, then skip, otherwise show and add into the array.

Option 2

While making the query, use DISTINCT(col_name) to get only the unique values.

Upvotes: 0

Arun
Arun

Reputation: 760

Please change this script to

while($row = mysql_fetch_row($result)) {
    echo "<tr>";           
    echo "<td>".$row['Location']."</td>";  
    echo "<td>".$row['Vessel ']."</td>"; 
    echo "</tr>";
 }

Upvotes: 1

Related Questions