I have a table like this :
No | Name Product | Type | Num of Units |
---|---|---|---|
1 | ADA | B112 | 3 Pcs |
2 | ADA | B253 | 1 Pcs |
3 | ADA | K23 | 6 Pcs |
4 | DUZK | l1 | 10 Pcs |
5 | DUZK | l5 | 10 Pcs |
6 | Naro | NX | 1 Pcs |
I have this SQL :
$query = "SELECT *, GROUP_CONCAT(`Code Unit`) AS Codeunit, COUNT(`Code Unit`) AS NoU FROM `stock goods` GROUP BY `Name Product`, `Type` ORDER BY `Name Product`, `Type`";
NoU : Num of Units
Actually I have Code Units in my table
Here is my code:
echo "<table id='customers'>";
echo "<tr>
<th id='No'>Nomor</th>
<th id='nameproduct'>Name Product</th>
<th id='type'>Type</th>
<th id='NoU'>Num of Units</th>
<th id='Click'>Botton Click</th>
</tr>";
$nomor_urut = 1;
$nomy = 1;
while ($row = mysqli_fetch_assoc($result)) {
$nomy = 1; // Initialize $nomy here
echo "<tr>";
echo "<td>" . $nomor_urut."</td>";
echo "<td>" . $row["Name Product"] . "</td>";
echo "<td>" . $row["Type"] . "</td>";
echo "<td>" . $row["NoU"] . "</td>";
$Type2 = explode(',', $row["Type"]);
$Kodeunits = explode(',', $row["Kodeunit"]);
$dara = $row["Type"] . " - " . $row["Jumlah"] . "<br>";
echo "<td><button onclick='myFunction(" . json_encode($row["Nama Produk"]) . "," . json_encode($row["Type"]) . ",". json_encode($Kodeunits) . ")'>List Stock</button></td>";
echo "</tr>";
$nomor_urut++;
}
echo "</table>";
I hope to convert to the table like this:
No | Name Product | Type | Num of Units |
---|---|---|---|
1 | B112 | 3 Pcs | |
2 | ADA | B253 | 1 Pcs |
3 | K23 | 6 Pcs | |
4 | l1 | 10 Pcs | |
5 | DUZK | l5 | 10 Pcs |
6 | Naro | NX | 1 Pcs |
I hope every same name of Name Product would be pressed into 1 row so it looks neat
3
Answers
First in your php code, determine consecutive identical
Name Product
by adding other identifiers, followed by the rowspan tag to assemble your table_td.You have to count the number of product with same name. As your Database query has a
group by
andorder by
clause so the products with same name will be grouped together. Then you have to addrowspan
in the product name<td>
Result:
The main problem with your code is that you are very quick to
echo
the results as fast as you get them, so by the time you get the second record having the same product name as the previous one, you’ve already written the first one. Instead, you need to grasp the concept of separation of concerns, a principle, which, in your case was violated by assuming that you want/need to echo out all the results as soon as you get them. But it’s actually not the case, because you will need to first parse the records in order to know what therowspan
will end up to be.Instead of echoing everything, separate the echoing into a function, which I will call
echoTemplate
here and do something like this:And then implement
echoTemplate
so that it actually echoes out the stuff you generated.