Issue with Group by in PHP - php

My database design : http://i.stack.imgur.com/3Rm2e.png
I am trying to use below code :
$myselect = mysql_query("
SELECT
reason.ReasonName,
tblexam.EXAMDATE,
tblexam.EXAMTIME,
prefix.PREFIXABB,
studentmaster.STUDENTNAME,
studentmaster.STUDENTSURNAME,
studentmaster.STUDENTCODE,
program.PROGRAMNAME,
course.COURSENAMEENG
FROM
reason,
formlate,
tblexam,
studentmaster,
prefix,
program,
course
WHERE
reason.ReasonID = formlate.ReasonID AND
formlate.CLASSID = tblexam.CLASSID AND
formlate.COURSEID = formlate.COURSEID AND
formlate.ROOMID = formlate.ROOMID AND
prefix.PREFIXID = studentmaster.PREFIXID AND
formlate.STUDENTID = studentmaster.STUDENTID AND
program.PROGRAMID = studentmaster.PROGRAMID AND
course.COURSEID = tblexam.COURSEID
GROUP BY
reason.ReasonID,studentmaster.STUDENTID
ORDER BY
reason.ReasonID ASC");
<body>
<?php $i =1;
while($rowfet = mysql_fetch_array($myselect)){
?>
<h2><?php echo $rowfet['ReasonName']; ?></h2>
<h3><?php echo DateThai($rowfet['EXAMDATE']) . ' ' . MorningEvening($rowfet['EXAMTIME']); ?></h3>
<table width="100%" border="1">
<thead>
<tr>
<th>No.</th>
<th>studentid </th>
<th>Fullname </th>
<th>Program </th>
<th>Coursename </th>
</tr>
</thead>
<tbody>
<tr>
<td align="center"><?php echo $i; ?></td>
<td><?php echo $rowfet['STUDENTCODE']; ?></td>
<td><?php echo $rowfet['PREFIXABB'] . $rowfet['STUDENTNAME'] . ' '.$rowfet['STUDENTSURNAME']; ?></td>
<td><?php echo $rowfet['PROGRAMNAME']; ?></td>
<td><?php echo $rowfet['COURSENAMEENG']; ?></td>
</tr>
</tbody>
</table>
<?php $i++; } ?>
but it shows the result like :
Reason1
10 Jan 2015 (Morning)
| No | studentid | Fullname | Program | Coursename |
-------------------------------------------------------
| 1 | 111111 | John | ProgA | Math |
---------------------------------------------------------
Reason1
10 Jan 2015 (Morning)
| No | studentid | Fullname | Program | Coursename |
-------------------------------------------------------
| 2 | 2222222 | Jane | ProgB | Math |
-----------------------------------
Reason2
10 Jan 2015 (Evening)
| No | studentid | Fullname | Program | Coursename |
-------------------------------------------------------
| 3 | 3333333 | Hawk | ProgB | Math |
-----------------------------------
I want the result to show like :
Reason1
10 Jan 2015 (Morning)
| No | studentid | Fullname | Program | Coursename |
-------------------------------------------------------
| 1 | 111111 | John | ProgA | Math |
---------------------------------------------------------
| 2 | 2222222 | Jane | ProgB | Math |
-----------------------------------
Reason2
10 Jan 2015 (Evening)
| No | studentid | Fullname | Program | Coursename |
-------------------------------------------------------
| 1 | 3333333 | Hawk | ProgB | Math |
---------------------------------------------------------
I want to group table by
Reasonname
Examdate
Examtime
Please help, I'm a newbie.
I've create database in SQLFiddle Here this please try and help:
SQLFiddle

considered that you have a sql result that looks like this, ordered by reason, date and time :
reason.reasonName | examDate | examTime | prefix | studentName | studentSurname | studentCode | ProgramName | courseName
with a few records, like :
1 | someDate1 | someTime1 | A | James | Jim | 123 | PA | PACourse
1 | someDate1 | someTime1 | A | Tommy | Tim | 222 | PC | PCCourse
1 | someDate2 | someTime2 | B | James | Jim | 123 | PB | PBCourse
2 | someDate1 | someTime1 | C | Jamie | Jam | 444 | PD | PDCourse
2 | someDate1 | someTime1 | E | Willy | Wil | 555 | PE | PECourse
2 | someDate2 | someTime2 | F | Cathy | Cat | 777 | PF | PFCourse
2 | someDate2 | someTime2 | G | David | Dav | 844 | PL | PLCourse
2 | someDate3 | someTime3 | L | James | Jim | 123 | PM | PMCourse
3 | someDate4 | someTime4 | W | Ibear | Ibe | 999 | PX | PXCourse
Here, you get this kind of data, you have,
for reason 1 :
2 students with exam at the same day/time (time1)
1 student with axam at another time (time2)
for reason 2 :
2 students with exam at the same day/time (time1)
2 students with exam at the same day/time (time2)
1 student with exam at another time (time3)
for reason 3 :
1 student with exam at time 4
SO, you want to display :
2 tables for reason 1 (time1 / time2)
3 tables for reason 2 (time1 / time2 / time3)
1 table for reason 3
CONSIDERED that the table, when you get it from your SQL is REALLY oredered like what I wrote above, you have to make your checks on fetch :
<?php
//YOU WILL HAVE TO CHECK THESE VARS TO MAKE IT CLEAR, IF SAME TABLE OR NOT
$i = false;
//I use $i as a table detector, false at start, once a table has been opened it is turned as true
$reason = "";
//I will keep the latest reasonName in this
$examDate = "";
//I will keep the latest examDate in this
$examTime = "";
//I will keep the latest examTime in this
$yourDisplay = "";
//In yourDisplay, i keep the text i have to display (tables, data...)
$closeTable = "</tbody></table>";
//This is the code you need to close a table.
while($rowfet = mysql_fetch_array($myselect)){
if(($rowfet['ReasonName']!=$reason)||(DateThai($rowfet['EXAMDATE'])!=$examDate)||(MorningEvening($rowfet['EXAMTIME'])!=$examTime)){
//YOU GET HERE IF YOU HAVE DIFFERENT REASON/DATE/TIME, SO YOU HAVE TO MAKE A NEW TABLE
$reason = $rowfet['ReasonName'];
$examDate = DateThai($rowfet['EXAMDATE']);
$examTime = MorningEvening($rowfet['EXAMTIME']);
//NOW CHECK IF YOU ALREADY HAVE WRITTEN A TABLE BEFORE
if($i == true){
//You already have written a table before
$yourDisplay.=$closeTable;
}else{
//This is the first table you write
$i=true;
}
$yourDisplay.=" <h2>".$reason."</h2>
<h3>".DateThai($examDate)." ".MorningEvening($examTime)."</h3>
<table width='100%' border='1'>
<thead>
<tr>
<th>No.</th>
<th>studentid</th>
<th>fullname</th>
<th>Program</th>
<th>Coursename</th>
</tr>
</thead>
<tbody>
<tr>
<td>".$rowfet['STUDENTCODE']."</td>
<td>".$rowfet['PREFIXABB']." ".$rowfet['STUDENTNAME']." ".$rowfet['STUDENTSURNAME']."</td>
<td>".$rowfet['PROGRAMNAME']."</td>
<td>".$rowfet['COURSENAMEENG']."</td>
</tr>";
}else{
//YOU ARE ALREADY IN A TABLE! WITH SAME REASON/TIME/DATE
//YOUR RECORD JUST NEEDS TO BE ADDED IN A NEW LINE
$yourDisplay.="<tr>
<td>".$rowfet['STUDENTCODE']."</td>
<td>".$rowfet['PREFIXABB']." ".$rowfet['STUDENTNAME']." ".$rowfet['STUDENTSURNAME']."</td>
<td>".$rowfet['PROGRAMNAME']."</td>
<td>".$rowfet['COURSENAMEENG']."</td>
</tr>";
}
}
//ONCE OUT, CLOSE THE LAST TABLE AND DISPLAY YOUR DATA
if($i==1){
$yourDisplay.=$closeTable;
}
echo $yourDisplay;
?>
In My Opinion, this kind of approach should solve your problem IF THE SQL QUERY returns the rows as explained above. (seems like it is the case)
EDIT :
You asked to "not display" the reasonname if it was the same, so just look at the line you see this :
$yourDisplay.=" <h2>".$reason."</h2>
<h3>".DateThai($examDate)." ................ code continue
and replace it with this :
if($rowfet['ReasonName']!=$reason){
$yourDisplay.="<h2>".$reason."</h2>";
}
$yourDisplay.="<h3>".DateThai($examDate)." ".MorningEvening($examTime)."</h3>
<table width='100%' border='1'>
//.... continue the code

You're looping through all your rows and creating a table for each of the rows.
What you want to do is to create a new table only if a sequence of a new ReasonName starts.
$myselect = mysql_query("SELECT reason.ReasonName,tblexam.EXAMDATE,tblexam.EXAMTIME,prefix.PREFIXABB,studentmaster.STUDENTNAME,studentmaster.STUDENTSURNAME,studentmaster.STUDENTCODE,program.PROGRAMNAME,course.COURSENAMEENG FROM reason, formlate, tblexam, studentmaster,prefix, program, course WHERE reason.ReasonID = formlate.ReasonID AND formlate.CLASSID = tblexam.CLASSID AND formlate.COURSEID = formlate.COURSEID AND formlate.ROOMID = formlate.ROOMID AND prefix.PREFIXID = studentmaster.PREFIXID AND formlate.STUDENTID = studentmaster.STUDENTID AND program.PROGRAMID = studentmaster.PROGRAMID AND course.COURSEID = tblexam.COURSEID GROUP BY reason.ReasonID,studentmaster.STUDENTID ORDER BY reason.ReasonID ASC");
<body>
<?php $i =1;
while($rowfet = mysql_fetch_array($myselect)){
?>
<h2><?php echo $rowfet['ReasonName']; ?></h2>
<h3><?php echo DateThai($rowfet['EXAMDATE']) . ' ' . MorningEvening($rowfet['EXAMTIME']); ?></h3>
<table width="100%" border="1">
<thead>
<tr>
<th>No.</th>
<th>studentid </th>
<th>Fullname </th>
<th>Program </th>
<th>Coursename </th>
</tr>
</thead>
<tbody>
<?php echo "You should create a loop here to loop through your ReasonNames"; ?>
<tr>
<td align="center"><?php echo $i; ?></td>
<td><?php echo $rowfet['STUDENTCODE']; ?></td>
<td><?php echo $rowfet['PREFIXABB'] . $rowfet['STUDENTNAME'] . ' '.$rowfet['STUDENTSURNAME']; ?></td>
<td><?php echo $rowfet['PROGRAMNAME']; ?></td>
<td><?php echo $rowfet['COURSENAMEENG']; ?></td>
</tr>
<?php echo "Your loop should end here"; ?>
</tbody>
</table>
<?php $i++; } ?>

Related

Can I hide data on the table that has a specific or special values like zero? PHP & MySQL

Problem: I need to hide the data BUT not to delete it from the database that has a value or amount of zero or none value. Is there any possibilities to achieve this problem?
I just need to remove it from the bootstrap table
here is what my table looks like right now.
--------------------------------------
| id | amount | name | price |
| 1 | 3000 | John | 200 |
| 2 | 0 | John | 100 |
| 3 | 0 | John | 200 |
| 4 | 3000 | Pat | 400 |
--------------------------------------
The problem is there is the value of zero that should not be seen on my table, can that be solved by hiding or removing it?
To put it simply the table must be look like this
--------------------------------------
| id | amount | name | price |
| 1 | 3000 | John | 200 |
|------------------------------------
| 4 | 3000 | Pat | 400 |
--------------------------------------
Here is my code
<?php
//Fetch data
$host = "local";
$username = "name";
$password = "";
$database = "dbname";
try {
$connect = new PDO("mysql:host=$host;dbname=$database",$username,$password);
$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = "SELECT * FROM cabinqr_logs";
$data = $connect->query($query);
?>
<?php foreach($data as $row)
{?>
<tr>
<th scope="row"><?php echo $row["passenger"] ?></th>
<td><?php echo $row["flight_no"] ?></td>
<td><?php echo $row["amount"] ?></td>
<td><?php echo $row["date_time"] ?></td>
<td><?php echo $row["crew_name"] ?></td>
</tr>
</tbody>
<?php
}
}
catch (PDOException $error)
{
$error->getMessage();
}
?>
You just need to include a WHERE clause which says only to select rows with a value greater than zero in them...
$query = "SELECT * FROM cabinqr_logs WHERE amount > 0";

What should i do with custom GROUP BY in sql and php?

I want to make sub group in group by (SQL).
in my case, I want to make classified detail in group detail which it come from two different column, for more detail, check this out :
I've sql table like this :
+----+-------+--------+-------+
| No | data1 | detail | price |
+----+-------+--------+-------+
| 1 | ID1 | Food | $ 100 |
| 2 | ID1 | Drink | $ 25 |
| 3 | ID2 | Drink | $ 25 |
| 4 | ID1 | Snack | $ 50 |
| 5 | ID2 | Snack | $ 50 |
+----+-------+--------+-------+
I want to make result in my php page like this :
+----+-------+--------+-------+
| No | detail_lunch | price |
+----+-------+--------+-------+
| 1 | Food | |
| | - ID1 | $ 100 |
| 2 | Snack | |
| | - ID1 | $ 25 |
| | - ID2 | $ 25 |
| 3 | Drink | |
| | - ID1 | $ 10 |
| | - ID2 | $ 10 |
+----+-------+--------+-------+
I already tried with GROUP CONCAT as below :
Controller :
$d['data'] = $this->db->query("select detail_item, GROUP_CONCAT (detail) detail_lunch
from table ORDER BY detail_lunch ASC");
Views :
<?php
foreach($data->result_array() as $d)
{
?>
<tr>
<td><?php echo $no; ?></td>
<td><?php echo $d['detail_lunch']; ?></td>
<td><?php echo $d['price']; ?></td>
</tr>
<?php
$no++;
}
?>
My code above not working,
is there any suggestion to solve my problem?
thanks...
GROUP BY is not needed since you're not using an aggregate function (combining two rows of values into a single value), you are attempting to create a pivot table, (joining two columns under a related column as multiple rows). You only need to ORDER BY detail ASC, data1 ASC, iterate over the resultset to display the detail when it changes, otherwise display the data1 and price
Example: https://3v4l.org/7tVDS
Query:
$data = $this->db->query('SELECT data1, detail, price
FROM table ORDER BY detail ASC, data1 ASC');
View:
<?php
//...
$no = 1;
$currentDetail = null;
foreach ($data->result_array() as $d) {
if ($d['detail'] !== $currentDetail) { ?>
<!-- Only Show the Detail when changed -->
<tr>
<td><?php echo $no++; ?></td>
<td><?php echo $d['detail']; ?></td>
<td> </td>
</tr>
<?php } ?>
<!-- Always show the data1/price on subsequent row -->
<tr>
<td> </td>
<td>- <?php echo $d['data1']; ?></td>
<td><?php echo $d['price']; ?></td>
</tr>
<?php
$currentDetail = $d['detail'];
} ?>
Result:
| 1 | Food |
| - ID1 | $ 100 |
| 2 | Drink |
| - ID1 | $ 25 |
| - ID2 | $ 25 |
| 3 | Snack |
| - ID1 | $ 50 |
| - ID2 | $ 50 |
Alternatively you can manipulate how the data is displayed in your view, such as using an unordered list ul in the detail table column td along with price. By using PHP to organize the values how you would like them to be displayed in your view, in an organized associative array.
Example: https://3v4l.org/8sIrR
$dataArray = [];
foreach ($data as $d) {
if (!array_key_exists($d['detail'], $dataArray)) {
$dataArray[$d['detail']] = [];
}
$dataArray[$d['detail']][] = $d;
}
//...
$no = 1;
foreach ($dataArray as $detail => $d) { ?>
<tr>
<td><?php echo $no++; ?></td>
<td>
<?php echo $detail; ?>
<ul>
<?php foreach ($d as $v) { ?>
<li><?php echo $v['data1']; ?> <?php echo $v['price']; ?></li>
<?php } ?>
</ul>
</td>
</tr>
<?php } ?>
Query is the problem .
Select detail_lunch from table group by details.
Then you can use if statement on that result.
I will update my answer after I get to work on my computer.

how to make table using php foreign key

I have a question about PHP query.
I have 2 tables.
First Table:
|id_table1 | first_name | last_name |
|----------|------------|-----------|
| 1 | John | Doe |
| 2 | Doe | John |
Second Table:
|id_table2 | hobby | age | id_table1|
|----------|--------|-----|----------|
| 1 |football| 17 | 1 |
| 2 |swimming| 18 | 2 |
I want to make table like this:
| John Doe | | Doe John |
|----------------| |--------|------|
| Hobby | Age | | Hobby | Age |
|----------|-----| |--------|------|
| football | 17 | |swimming| 19 |
|basketball| 18 |
What is the syntax to make that table in php? May be using foreach, but how?
Thanks.
The code
<?php
$ftable="select * from ftable";
$stable="select * from stable";
$ftable1= mysqli_query($conn, $ftable);
$stable1= mysqli_query($conn, $stable);
foreach ($ftable as $row) {
echo "
<tr>
<th style='text-align: center' colspan='2'>".$row['first_name']."</th>
</tr>
<tr>
<th>Hobby</th>
<th>Age</th>
</tr>";
foreach ($ftable1 as $row1) {
echo "
<tr>
<td>".$row1['hobby']."</td>
<td>".$row1['age']."</td>
<tr>";
}
}
?>
Just save the id number of ftable, then test for it in your 'for' loop for the second table, like this:
<?php
$ftable="select * from ftable";
$stable="select * from stable";
$ftable1= mysqli_query($conn, $ftable);
$stable1= mysqli_query($conn, $stable);
foreach ($ftable1 as $row) {
$id_table1 = $row["id_table1"];
echo "<tr><th style='text-align: center' colspan='2'>"
.$row['first_name']."</th></tr>"
."<tr><th>Hobby</th>"
."<th>Age</th></tr>";
foreach ($stable1 as $row1) {
if ($row1["id_table1"] == $id_table1) {
echo "<tr><td>$row1['hobby']</td><td>$row1['age']</td></tr>";
}
}
}

display table group by category using php

my database design is like this
-- Table Reason
--------------------------
| reasonid | reasonname |
--------------------------
| 1 | reason1 |
| 2 | reason2 |
--------------------------
-- Table Student
----------------------------
| studentid | studentname |
----------------------------
| 1 | John |
| 2 | Jane |
| 3 | Hulk |
----------------------------
-- Table form
-----------------------------------
| formid | studentid | reasonid |
-----------------------------------
| 1 | 1 | 1 |
| 2 | 2 | 2 |
| 3 | 3 | 1 |
-----------------------------------
I want to show data table like :
reason1
| 1 | John |
| 2 | Hulk |
reason2
| 1 | Jane |
I have tried below code but the result is not groupBy reason
<?php $i =1;
while($rowfet = mysql_fetch_array($myselect)){ ?>
<h2><?php echo $rowfet['ReasonName']; ?></h2>
<table>
<thead>
<tr class="active">
<th>No.</th>
<th>StudentName</th>
</tr>
</thead>
<tbody>
<tr>
<td align="center"><?php echo $i; ?></td>
<td><?php echo $rowfet['STUDENTNAME']; ?></td>
</tr>
</tbody>
</table>
<?php $i++; } ?>
the result of this code is :
reason1
| 1 | John |
reason1
| 2 | Hulk |
reason2
| 3 | Jane |
You could do something like this:
outside while loop:
$lastReasonId = '';
inside while loop:
if($rowfet['reasonid'] != $lastReasonId){
// show heading
}
$lastReasonId = $rowfet['reasonid'];
But your code is far from ok. The $i++ thing is not doing anything, you should probably echo $rowfet['studentid'] there.
And you are using deprecated mysql code.

How to echo specific data in loop with a condition specific to the last row

For an accounting system, I'm using PHP & MySQL. I've two tables "GROUP" and "ACHEADS".
In the GROUP table, I have:
---------------------
| id (AI) | group |
---------------------
| 1 | Group 1 |
| 2 | Group 2 |
---------------------
In the ACHEADS table, I have:
-----------------------------------------
| id (AI) | ac_head | amount | j_id |
-----------------------------------------
| 1 | Something 1 | 2000 | 1 |
| 2 | Something 2 | 1000 | 1 |
| 3 | Something 3 | 5000 | 2 |
| 4 | Something 4 | 4000 | 2 |
| 5 | Something 5 | 8000 | 2 |
-----------------------------------------
I've joined the two tables as GROUP.id <<->> ACHEADS.j_id
Now I need to preview the data like this:
----------------------------------------------
Particulars | Details | Total |
----------------------------------------------
Group 1 | | |
Something 1 | 2000 | |
Something 2 | 1000 | 3000 |
----------------------------------------------
Group 2 | | |
Something 3 | 5000 | |
Something 4 | 4000 | |
Something 5 | 8000 | 17000 |
----------------------------------------------
GRAND TOTAL | | 20000 |
------------------------------------==========
Challenges
The table will be dynamic and will generate within a PHP loop (I'm
using a WHILE loop)
Remember: it's a table and if I miss echoing a td, then the table will break up
Problems
When I'm using the loop it's echoing the data on the Details td
accurately. But the sum of the details row according to j_id is also
echoing in each td
Preview here:
----------------------------------------------
Particulars | Details | Total |
----------------------------------------------
Group 1 | | |
Something 1 | 2000 | 3000 |
Something 2 | 1000 | 3000 |
----------------------------------------------
Group 2 | | |
Something 3 | 5000 | 17000 |
Something 4 | 4000 | 17000 |
Something 5 | 8000 | 17000 |
----------------------------------------------
My thoughts
If I can check whether it is the last data of the query, if isset,
then echo the total amount with it's td. (But remember the
Challenge#2)
Does it require a foreach loop?
I failed
I tried checking max(id), it works fine in SQL, but can't use it in
condition within a loop.
(If you still can't understand me, then on the second phase, I'll post my code.)
I would do 2 loops:
Fetch id from GROUP
Fetch amount from ACHEADS based on j_id
This would look something like (non-tested code):
echo '<table><tr><td>Particulars</td><td>Details</td><td>Total</td></tr>';
$total = 0;
$q1 = "SELECT id FROM `GROUP`";
$res1 = mysqli_query($q1);
while($row1 = mysqli_fetch_assoc($res1)) {
echo
$group_total = 0;
$j_id = $row1[id];
$q2 = "SELECT ac_head, amount FROM ACHEADS WHERE j_id = $j_id";
$res2 = mysqli_query($q2);
while($row2 = mysqli_fetch_assoc($res1)) {
echo '<tr><td>' . $row2[ac_head] . '</td>';
echo '<td>' . $row2[amount] . '</td></tr>';
$group_total = $group_total + $row2[amount];
$total = $total + $row[amount];
}
echo '<tr><td colspan="3" align="right">' . $group_total . '</td></tr>';
}
echo '<tr><td>GRAND TOTAL</td>';
echo '<td colspan="2" align="right">' . $total . '</td></tr>';
echo "</table>";
njk rockz!
It worked nicely. Thanks a lot, brother - it helped me a lot, I can't explain.
Here is my final code:
<tr style="background: #000; color:#fff;">
<th style="width:150px;">Particulars</th>
<th>Details</th>
<th>Amount</th>
</tr>
<tr>
<td>Opening Balance</td>
<td></td>
<td>500000</td> <!-- till not dynamic -->
</tr>
<?php
$total = 0;
$se = "SELECT * FROM group";
$res = mysql_query($se) or die (mysql_error());
while ($row = mysql_fetch_array($res))
{
?>
<tr>
<td colspan="3" style="font-weight:bold;"><?php echo $row['group']; ?></td>
</tr>
<tr>
<?php
$group_total = 0;
$se1 = "SELECT ac_head, amount FROM `acheads` WHERE `j_Id` = '".$row['id']."'";
$res1 = mysql_query($se1) or die (mysql_error());
while ($row1 = mysql_fetch_array($res1))
{
$group_total = $group_total + $row1['amount'];
?>
<td><?php echo $row1['ac_head']; ?></td>
<td><?php echo $row1['amount']; ?></td>
<td> </td>
</tr>
<?php
}
echo '<tr><td colspan="3" align="right">' . $group_total . '</td></tr>';
}
?>
</table>
</code>

Categories