How declare the data in column mysql - php

Can someone help me, I wanna declare the data from column "status".
If 'green' then the value is 1.
If 'yellow' the value is 2.
If 'red' the value is 3.
And then all of that value can make line graph using PHP language.
name: 'Data Status',
data: [
<?php
$sql = "SELECT * FROM monitoring";
$result = mysqli_query($koneksi, $sql);
while ($data = mysqli_fetch_array($result))
{
?>
<?php echo $data["status"]?>, <?php
}?>
]
But I know the data cannot load properly because the type data is string.
+---------+------------+----------+----------+
| id_data | time | status | date |
+---------+------------+----------+----------+
| 1 | 05.00 | green | 01-01-18 |
| 2 | 05.30 | green | 02-01-18 |
| 3 | 05.30 | red | 03-01-18 |
| 4 | 05.30 | green | 04-01-18 |
| 5 | 05.15 | yellow | 05-01-18 |
| 6 | 05.20 | yellow | 06-01-18 |
| 7 | 05.11 | red | 07-01-18 |
| 8 | 05.05 | red | 08-01-18 |
| 9 | 05.22 | green | 09-01-18 |
+---------+------------+----------+----------+

<?php
$sql = "SELECT * FROM monitoring";
$result = mysqli_query($koneksi, $sql);
while ($data = mysqli_fetch_array($result)) {
switch ($data["status"]){
case 'green':
$value = 1;
break
case 'yellow':
$value = 2;
break;
case 'red':
$value = 3;
break;
default:
$value = 0;
break;
}
echo $data["status"] . ' ' . $value;
}

Possible the easiest would be a case statement in the sql
SELECT
`id_data`,
`time`,
`date`,
case
when `status`='green' then 1
when `status`='yellow' then 2
when `status`='red' then 3
end as `status`
FROM `monitoring`

Related

How to display mysql data as table header and then all data related to that result as table data in html

I'm working on a venue programming system for festivals to update our current system of just using loads of spreadsheets. I'm trying to figure out a way to display a table that shows all subvenues related to a festival as table headings and then all timeslots related to that subvenue as table columns. I want it to look something like this at the end.
screenshot of current spreadsheet used:
The idea is that you will be able to click on one of the free timeslots, and open a modal to allocate a show to that slot or display shows already attached to it. Ideally each subvenue will be drag and dropped into order but these are problems for later.
So far I'm trying to use a loop to create a table with only 1 column. have an sql query return the header and then inside that return loop have another sql query that returns all of the timeslots, then close the first loop. but this is only displaying 1 table and not looping round to return the others.
Code is
<?php
//selects subvenue
$sql = "SELECT *
FROM Subvenue S
JOIN Venue V
ON S.venueId = V.venueId
JOIN festvenue FV
ON V.venueId = FV.venueId
WHERE FV.festId = $festId;";
$result = mysqli_query($conn, $sql);
if (!$result) die ("Database access failed");
$rows = $result->num_rows;
//starts loop to display subvenues
for ($j = 0 ; $j < $rows ; ++$j) {
$row = $result->fetch_array(MYSQLI_NUM);
$subvenueId = htmlspecialchars($row[0]);
$subvenueName = htmlspecialchars($row[2]);
echo <<<_END
<table>
<tr>
<th id="$subvenueId">$subvenueName<th>
</tr>
_END;
$sql = "SELECT * FROM TimeSlot
WHERE subVenId = $subvenueId
ORDER BY (start >= '05:00:00') desc, start;";
$result = mysqli_query($conn, $sql);
if (!$result) die ("Database access failed");
$rows = $result->num_rows;
for ($j = 0 ; $j < $rows ; ++$j) {
$row = $result->fetch_array(MYSQLI_NUM);
$timeId = htmlspecialchars($row[0]);
$type = htmlspecialchars($row[3]);
$start = htmlspecialchars($row[4]);
$end = htmlspecialchars($row[5]);
$length = htmlspecialchars($row[8]);
echo <<<_END
<tr id="$timeId" class="timeslot-time">
<td class="$type-$length">$start - $end</td>
</tr>
_END;
}
echo "</table>";
}
?>
The sample data I have is below
Subvenue Table
+----------+---------+------------------------+
| subVenId | venueId | subVenName |
+----------+---------+------------------------+
| 1 | 2 | Subvenue 1 |
| 2 | 2 | subvenue 2 |
+----------+---------+------------------------+
timeslot Table
+--------+--------+----------+-------+----------+----------+--------+
| timeId | festId | subVenId | type | start | end | length |
+--------+--------+----------+-------+----------+----------+--------+
| 1 | 11 | 1 | show | 12:00:00 | 13:00:00 | 60 |
| 2 | 11 | 1 | show | 13:30:00 | 14:30:00 | 60 |
| 3 | 11 | 1 | break | 13:00:00 | 13:30:00 | 30 |
| 4 | 11 | 1 | break | 14:30:00 | 15:00:00 | 30 |
| 5 | 11 | 1 | show | 15:00:00 | 16:00:00 | 60 |
| 6 | 11 | 2 | show | 16:30:00 | 17:30:00 | 60 |
| 7 | 11 | 2 | show | 18:00:00 | 19:00:00 | 60 |
| 8 | 11 | 2 | show | 19:30:00 | 20:30:00 | 60 |
| 9 | 11 | 1 | show | 21:00:00 | 22:00:00 | 60 |
| 10 | 11 | 2 | show | 22:30:00 | 23:30:00 | 60 |
+--------+--------+----------+-------+----------+----------+--------+
I'm not even sure a table it the best thing for this or would lists or something else be better?
At the end I want it to display
+-------------------+. +-------------------+
| subvenue 1 | | subvenue 2 |
+-------------------+. +-------------------+
| 12:00:00-13:00:00 | | 16:30:00-17:30:00 |
| 13:30:00-14:30:00 | | 18:00:00-19:00:00 |
| 13:00:00-13:30:00 | | 19:30:00-20:30:00 |
| 14:30:00-15:00:00 | | 22:30:00-23:30:00 |
| 15:00:00-16:00:00 |. +-------------------+
| 21:00:00-22:00:00 |
+-------------------+
etc
I've managed to figure this out. I decided to output a series of lists instead of using a table.
Apart from that my main fix was instead of using the same $sql and $stmt variables in the mySQL query I used $subSql and $subStmt for the second query.
require_once "header.php";
$festId = mysqli_real_escape_string($conn, $_GET["festival_Id"]);
?>
<div id="programming" class="tabcontent">
<h2 >Programming</h2><br>
<?php
//gets the subvenue and starts first loop
$sql = "SELECT *
FROM Subvenue S
JOIN Venue V
ON S.venueId = V.venueId
JOIN festvenue FV
ON V.venueId = FV.venueId
WHERE FV.festId = ?;";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)) {
header("location: ../festival.php?error=sqlerror&festival_Id".$festId);
exit();
}
else {
mysqli_stmt_bind_param($stmt, "s", $festId);
mysqli_stmt_execute($stmt);
$result = $stmt->get_result();
$rows = $result->num_rows;
for ($j = 0 ; $j < $rows ; ++$j)
{
$row = $result->fetch_array(MYSQLI_NUM);
$subVenueId = htmlspecialchars($row[0]);
$subVenueName = htmlspecialchars($row[2]);
echo <<<_END
<div id="$subVenueId" class="programme">
<ul>
<li class="programme-heading">$subVenueName</li>
<ul>
_END;
//select all timeslots with that subvenue
$subSql = "SELECT * FROM TimeSlot
WHERE subVenId = ?
ORDER BY (start >= '05:00:00') desc, start;";
$subStmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($subStmt, $subSql)) {
header("location: ../festival.php?
error=sqlerror&festival_Id".$festId);
exit();
}
else {
mysqli_stmt_bind_param($subStmt, "s", $subVenueId);
mysqli_stmt_execute($subStmt);
$subResult = $subStmt->get_result();
while ($row = mysqli_fetch_assoc($subResult)) {
$timeId = htmlspecialchars($row['timeId']);
$type = htmlspecialchars($row['type']);
$start = htmlspecialchars($row['start']);
$end = htmlspecialchars($row['end']);
$length = htmlspecialchars($row['length']);
echo <<<_END
<li id="[$timeId" class="$type-$length">$start - $end</li>
_END;][1]
}
}
echo "</ul></ul></div>";
}
}
That looks exactly how I wanted it. in the initial question

Switch Case Looping PHP

i was very frustated, i've tried many method but didn't find my expexted result. I have this data in my table database:
| PartID | HasilProduksi |QtyProduksi|
|----------------------|------------------|-----------|
| BLAP-FG152-PF-KGX | Repair | 1 |
| AWDX-FG002-HN-KGX | Reject | 90 |
| HMXX-FG022-EG-KGX | Good | 100 |
| ECJX-FG018-AV-MCM | Good | 111 |
and i want to create report with result :
| | ACTUAL |
| PartID | ---------------------|
| |Good | Repair | Reject|
|----------------------|-----|--------|-------|
| BLAP-FG152-PF-KGX | 0 | 1 | 0 |
| AWDX-FG002-HN-KGX | 0 | 0 | 90 |
| HMXX-FG022-EG-KGX | 100 | 0 | 0 |
| ECJX-FG018-AV-MCM | 111 | 0 | 0 |
and i'm using switch case method but the result is not like with my expected result. And This is my code :
$sqlc = "SELECT * FROM $db_dthp WHERE IdBukti='$id_bukti'";
$qc = mysqli_query($conn, $sqlc);
$c = 0; $good=0; $reject=0; $repair=0;
while ($rc = mysqli_fetch_assoc($qc)) {
switch ($rc['HasilProduksi']) {
case 'Good':
$good += (int) $rc['QtyProduksi'];
$datagood += (int) $rc['QtyProduksi'];
break;
case 'Reject':
$reject += (int) $rc['QtyProduksi'];
$datareject += (int) $rc['QtyProduksi'];
break;
case 'Repair':
$repair += (int) $rc['QtyProduksi'];
$datarepair += (int) $rc['QtyProduksi'];
break;
default:
break;
}
$c++;
}
$res['result'][$i]['data'][$b]['hp'][0]['good'] = number_format($good,0,'.','.');
$res['result'][$i]['data'][$b]['hp'][0]['reject'] = number_format($reject,0,'.','.');
$res['result'][$i]['data'][$b]['hp'][0]['repair'] = number_format($repair,0,'.','.');
Can you help me?
If you use this other query, you will have already your data and you don't need the switch in php. You will do the case in your query:
$sqlc="SELECT PartID,
CASE
WHEN HasilProduksi='Good' THEN QtyProduksi ELSE 0
END as Good,
CASE
WHEN HasilProduksi='Repair' THEN QtyProduksi ELSE 0
END as Repair,
CASE
WHEN HasilProduksi='Reject' THEN QtyProduksi ELSE 0
END as Reject
FROM $db_dthp WHERE IdBukti='$id_bukti';"
You can use mysql if to do this
SELECT PartID,IF(HasilProduksi ='Good',QtyProduksi,0)as
GOOD,IF(HasilProduksi ='Repair',QtyProduksi,0)as REPAIR,
IF(HasilProduksi ='Reject',QtyProduksi,0)as REJECT FROM
$db_dthp group by PartID

create a sequence for rows with similar ids using php

i have a datastructure similar to this
+---------+---------+
| id | value |
+---------+---------+
| 1 | value |
1 | value |
| 1 | value |
| 1 | value |
| 1 | value |
| 2 | value |
| 2 | value |
| 2 | value |
| 3 | value |
| 3 | value |
| 3 | value |
| | |
+---------+---------+
I am trying to update this table to look something like this
+---------+---------+
| id | value |
+---------+---------+
| 1 | value 0 |
1 | value 1 |
| 1 | value 2 |
| 1 | value 3 |
| 1 | value 4 |
| 2 | value 0 |
| 2 | value 1 |
| 2 | value 2 |
| 3 | value 0 |
| 3 | value 1 |
| 3 | value 2 |
| | |
+---------+---------+
To achieve this, i have written php script that looks like this
$query = "select count(*) as count,id, value from foo group by id";
$sql=$con->prepare($query);
$sql->execute();
$sql->setFetchMode(PDO::FETCH_ASSOC);
while($row=$sql->fetch()){
$id[] = $row['id'];
$count[] = $row['count'];
$value[] = $row['value'];
echo "<pre>";
}
$c=array_combine($id, $count);
foreach ($c as $key=>$value){
for($i=0;$i<=$value;$i++){
$postid = $key;
if($i==0){
$multiple = "multiple";
$newvalue= $value;
}
else{
$x=$i-1;
$multiple = "multiple_".$x;
echo $multiple . "<br>";
$query2 = "update foo set value = :multiple";
$sql2=$con->prepare($query2);
$sql2->bindValue(':multiple', $multiple);
$sql2->execute();
}
}
}
The problem is that the code returns the following results
+---------+---------+
| id | value |
+---------+---------+
| 1 | value_1 |
1 | value_1 |
| 1 | value_1 |
| 1 | value_1 |
| 1 | value_1 |
| 2 | value_1 |
| 2 | value_1 |
| 2 | value_1 |
| 3 | value_1 |
| 3 | value_1 |
| 3 | value_1 |
| | |
+---------+---------+
What can i be possibly be doing wrong?
Thanks #Shadow
Your query runs fine but returns the following results
+------+-----------------------------------------------+
| id | value |
+------+-----------------------------------------------+
| 1 | multiple_1_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0 |
| 1 | multiple_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1 |
| 1 | multiple_1_2_2_2_2_2_2_2_2_2_2_2_2_2_2_2_2 |
| 1 | multiple_1_3_3_3_3_3_3_3_3_3_3_3_3_3_3_3_3 |
| 2 | multiple_1_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0 |
| 2 | multiple_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1 |
| 2 | multiple_1_2_2_2_2_2_2_2_2_2_2_2_2_2_2_2_2 |
| 2 | multiple_1_3_3_3_3_3_3_3_3_3_3_3_3_3_3_3_3 |
| 3 | multiple_1_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0 |
| 3 | multiple_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1 |
| 3 | multiple_1_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0 |
+------+-----------------------------------------------+
You can do the update iterating and creating data in such a way:
<?php
$pdo = new PDO('mysql:host=localhost;dbname=test', 'root', '');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $pdo->prepare("SELECT * FROM foo");
$sth->execute();
$data = $sth->fetchAll(PDO::FETCH_ASSOC);
$response = array();
foreach ($data as $dataIndex => $dataValue) {
if (!isset($response[$dataValue["id"]]["count"])) {
$response[$dataValue["id"]]["count"] = 0;
} else {
$response[$dataValue["id"]]["count"] ++;
}
$response[$dataValue["id"]]["values"][$dataValue["pid"]] = "value_" . $response[$dataValue["id"]]["count"];
$sth = $pdo->prepare("UPDATE foo SET value = '{$response[$dataValue["id"]]["values"][$dataValue["pid"]]}' WHERE pid = {$dataValue["pid"]}");
$sth->execute();
}
?>
But try to do an update using the least iteration not to create as many database queries , example:
<?php
$pdo = new PDO('mysql:host=localhost;dbname=test', 'root', '');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $pdo->prepare("SELECT * FROM foo");
$sth->execute();
$data = $sth->fetchAll(PDO::FETCH_ASSOC);
$response = array();
$update = array();
foreach ($data as $dataIndex => $dataValue) {
$response[$dataValue["id"]]["id"] = $dataValue["id"];
if (!isset($response[$dataValue["id"]]["count"])) {
$response[$dataValue["id"]]["count"] = 0;
} else {
$response[$dataValue["id"]]["count"] ++;
}
$response[$dataValue["id"]]["values"][$dataValue["pid"]] = "value_" . $response[$dataValue["id"]]["count"];
$update[] = "UPDATE foo SET value = '{$response[$dataValue["id"]]["values"][$dataValue["pid"]]}' WHERE pid = {$dataValue["pid"]};";
}
$update = implode("",$update);
$sth = $pdo->prepare($update);
$sth->execute();
?>
Your update query
$query2 = "update foo set value = :multiple";
does not contain any where criteria, each time you call this query it updates the value field's value in all records.
Honestly, I would not really involve php in this update, would do it purely in sql using user defined variables and multi-table join syntax in the update:
update foo inner join (select #i:=0, #previd:=-1) as a
set foo.value=concat(foo.value,'_',#i:=if(id=#previd,#i+1,0),if(#previd:=id,'',''))
The subquery in the inner join initialises #i and #previd user defined variables. The 3rd parameter of the concat function determines the value #i to be concatenated to the value field. The 4th parameter of concat sets the #previd variable and returns an empty string not to affect the overall concatenation. Unfortunately, I do not have access to MySQL to test the query, but it should be a good starting point anyway.
UPDATE
The OP claims in the updated question that the query I provided creates the below resultset:
+------+-----------------------------------------------+
| id | value |
+------+-----------------------------------------------+
| 1 | multiple_1_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0 |
| 1 | multiple_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1 |
| 1 | multiple_1_2_2_2_2_2_2_2_2_2_2_2_2_2_2_2_2 |
| 1 | multiple_1_3_3_3_3_3_3_3_3_3_3_3_3_3_3_3_3 |
| 2 | multiple_1_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0 |
| 2 | multiple_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1 |
| 2 | multiple_1_2_2_2_2_2_2_2_2_2_2_2_2_2_2_2_2 |
| 2 | multiple_1_3_3_3_3_3_3_3_3_3_3_3_3_3_3_3_3 |
| 3 | multiple_1_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0 |
| 3 | multiple_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1 |
| 3 | multiple_1_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0 |
+------+-----------------------------------------------+
Tested my solution in sqlfiddle. I had to remove the order by clause, otherwise the query produced the results in line with the requirements stated in the question. See sqlfiddle for details.
The results in the updated question are likely the result of running the query in a loop multiple times. In simple words: you just copy pasted the query into your code and did not remove the loop, even when I pointed out, that this may be the reason of the results you received.

Number auto increase with other while function (PHP)

I want the queqe id auto increase start from 1
I have an mysql table call t1
mysql table t1 Data as below:
+----------+------------------+-------------+
| ID | Name | Status |
+----------+------------------+-------------+
| 1 | ABBCCC | 1 |
| 2 | BASDASD | 1 |
| 3 | ABBCCC | 1 |
| 4 | ABBCCC | 2 |
+-------------------------------------------+
I loop data in php like this:
$quserCA = DB::query("SELECT * FROM ".DB::table('jnbook_book')." WHERE Name = 'ABBCCC' ORDER BY id DESC LIMIT 20");
$nqCA = mysql_num_rows($quserCA);
while($ruserCA = DB::fetch($quserCA)){
$CAlist[] = $ruserCA;
}
$x = 1;
while($x <= $nqCA) {
//echo "The number is: $x <br>";
$x++;
}
I loop this in my htm like this:
<table>
<tr>
<td>Queqe ID</td><td>ID</td><td>Status</td>
</tr>
<!--{loop $CAlist $value}-->
<tr>
<td>{$x}</td><td>{$value[id]}</td><td>{$value[status]}</td>
</tr>
<!--{/loop}-->
</table>
But after that my table output as below show
+---------------+-------------------+----------------+
| Queqe ID | ID | Status |
+---------------+-------------------+----------------+
| 1 | 1 | 1 |
| 1 | 3 | 1 |
| 1 | 4 | 2 |
+----------------------------------------------------+
Actually what I want the table output as below
(I want the queqe id auto increase start from 1):
+----------+-----------------+-----------------+
| Queqe ID | ID | Status |
+----------+-----------------+-----------------+
| 1 | 1 | 1 |
| 2 | 3 | 1 |
| 3 | 4 | 2 |
+----------------------------------------------+
Thank you.
This should be done something like:
$x = 1;
while($ruserCA = DB::fetch($quserCA)){
// add a field, say `x` with number of a record:
$ruserCA['x'] = $x++;
$CAlist[] = $ruserCA;
}
In a template:
<td>{$value[x]}</td><td>{$value[id]}</td><td>{$value[status]}</td>

How to count the total of each group categorize by set from mysql

I may not use the proper subject of the problem. But here's the detail. I've got 3 tables of data 2 of them are set name and group name. The rest is data - user db. Here's the db.
set_name
+--------+-----------+
| set_id | set_title |
+--------+-----------+
| 1 | Set A |
+--------+-----------+
| 2 | Set B |
+--------+-----------+
group_db
+--------+-----------+--------+
| grp_id | grp_title | set_id |
+--------+-----------+--------+
| 1 | Grp. A | 1 |
+--------+-----------+--------+
| 2 | Grp. B | 1 |
+--------+-----------+--------+
| 3 | Grp. C | 1 |
+--------+-----------+--------+
| 4 | Grp. D | 1 |
+--------+-----------+--------+
| 5 | Grp. E | 1 |
+--------+-----------+--------+
| 6 | Grp. F | 2 |
+--------+-----------+--------+
user_db
+--------+-----------+
| usr_id | grp_id |
+--------+-----------+
| 1 | 1 |
+--------+-----------+
| 2 | 1 |
+--------+-----------+
| 3 | 2 |
+--------+-----------+
| 4 | 1 |
+--------+-----------+
| 5 | 3 |
+--------+-----------+
| 6 | 4 |
+--------+-----------+
| 7 | 5 |
+--------+-----------+
| 8 | 5 |
+--------+-----------+
| 9 | 5 |
+--------+-----------+
| 10 | 6 |
+--------+-----------+
According to the information provided above. I expect a summary table in which count all user and categorize by group and set. For example:
+-----+--------------------------------------------+--------+
| SET | Set A. | Set B. |
+-----+--------------------------------------------+--------+
|GROUP| Grp. A | Grp. B | Grp. C | Grp. D | Grp. E | Grp. F |
+-----+--------------------------------------------+--------+
| NUM | 3 | 1 | 1 | 1 | 3 | 1 |
+-----+--------------------------------------------+--------+
|TOTAL| 9 | 1 |
+-----+--------------------------------------------+--------+
And this is how I do.
<table>
<tr>
<?
$sql_set=mysqli_query($con,"SELECT *,count(group_db.grp_id) AS nGrp\n"
. "FROM set_name\n"
. "INNER JOIN group_db ON set_name.set_id=group_db.set_id\n"
. "GROUP BY set_name.set_id\n"
. "ORDER BY set_name.set_id asc");
echo "<td>SET</td>";
while($rec_set=mysqli_fetch_array($sql_set)){
echo "<td colspan=\"$rec_set[nGrp]\">$rec_set[set_title]</td>";
}
?>
</tr>
<tr>
<?
$sql_sGrp=mysqli_query($con,"SELECT * from group_db\n"
. "WHERE set_id='$rec_set[set_id]'\n"
. "ORDER BY grp_title asc");
echo "<td>GROUP</td>";
while($rec_sGrp=mysqli_fetch_array($sql_sGrp)){
echo "<td>$rec_sGrp[grp_title]</td>";
}
?>
</tr>
</table>
That's it. I don't know how to go further. Please be advice.
Ps. Should I make them all in multilevel array to make it easier?
I would do something like:
SELECT
*
FROM
user_db u
JOIN
group_db g ON u.grp_id = g.grp_id
JOIN
set_name s ON g.set_id = s.set_id
(EDIT: changed qry to this ^ which can be seen here: http://sqlfiddle.com/#!2/e749f/4)
And then in PHP:
$newArray = array();
while($rec_set=mysqli_fetch_array($sql_set)){
$newArray[$rec_set['set_title']][$rec_set['grp_title']] += 1;
}
which should give you a nice multidimensional array of the results that you can parse through however you want
And to give a table that looks like:
+-----+--------------------------------------------+--------+
| SET | Set A. | Set B. |
+-----+--------------------------------------------+--------+
|GROUP| Grp. A | Grp. B | Grp. C | Grp. D | Grp. E | Grp. F |
+-----+--------------------------------------------+--------+
| NUM | 3 | 1 | 1 | 1 | 3 | 1 |
+-----+--------------------------------------------+--------+
|TOTAL| 9 | 1 |
+-----+--------------------------------------------+--------+
I would use:
<tr>
<td>SET</td>
<?php foreach($newArray as $set => $group): ?>
<td colspan="<?=count($newArray[$set])?>"><?=$set?></td>
<?php endforeach; ?>
</tr>
<tr>
<td>GROUP</td>
<?php foreach($newArray as $set => $group): ?>
<?php foreach($group as $group_name => $amount): ?>
<td><?=$group_name?></td>
<?php endforeach; ?>
<?php endforeach; ?>
</tr>
<tr>
<td>NUMBER</td>
<?php foreach($newArray as $set => $group): ?>
<?php foreach($group as $group_name => $amount): ?>
<td><?=$amount?></td>
<?php $totals[$set] += $amount;?>
<?php endforeach; ?>
<?php endforeach; ?>
</tr>
<tr>
<td>TOTAL</td>
<?php foreach($newArray as $set => $group): ?>
<td colspan="<?=count($newArray[$set])?>"><?=$totals[$set]?></td>
<?php endforeach; ?>
</tr>
However, now that I look at how you would actually display it, if you really wanted a table that looked like you put, then a multidimensional array would probably not be the best way to loop through your data since all these loops are UGLY! (And it does not scale too well horizontally as you add more and more sets and groups). I did not check it for accuracy.
echo '<table>';
$rows = array('SET', 'GROUP', 'NUM', 'TOTAL');
$setids = array();
$grp_usercounts = array();
$set_usertotals = array();
foreach($rows as $key => $row){
echo "<tr> $rows </td>";
switch ($key){
case 0: //SET
$sql = "SELECT s.set_id, set_title, count(g.grp_id) nGrp
FROM set_name s
JOIN group_db g ON s.set_id = g.set_id
group by set_id";
$sql_set = mysqli_query($con, $sql);
while($rec_set=mysqli_fetch_array($sql_set)){
echo '<td colspan="'.$rec_set['nGrp'].'">'. rec_set['set_title'].'</td>';
$setids[$rec_set['set_id']] = $rec_set['nGrp'];
}
break;
case 1://GROUP
foreach($setids as $setid => $val){
$sql = "SELECT g.grp_id, grp_title, count(usr_id) nUsr
FROM group_db g
JOIN user_db u ON u.grp_id = g.grp_id
where set_id = $setid
group by g.grp_id order by grp_title";
$sql_set = mysqli_query($con, $sql);
$total = 0;
while($rec_set=mysqli_fetch_array($sql_set)){
echo '<td>'. $rec_set['grp_title'].'</td>';
$grp_usercounts[$rec_set['grp_id']] = $rec_set['nUsr'];
$total += $rec_set['nUsr'];
}
$set_usertotals[$setid] = $total;
}
break;
case 2://NUM
foreach($grp_usercounts as $key => $grp_usercount){
echo '<td>'. $grp_usercount .'</td>';
}
break;
case 3: //TOTAL
foreach($set_usertotals as $setid => $set_usertotal){
echo '<td colspan="'.$setids[$setid].'">'. $set_usertotal .'</td>';
}
break;
}
}
unset($setids);
unset($grp_usercounts);
unset($set_usertotals);
echo '</table>';

Categories