Display Table Rows Within Row - php

What I am trying to achieve best described in the example diagram below, in a html table. My table works fine with data from a MySQL database but all the data is printed in rows, which is correct, however I am required to display the data in the format below and the same format in Excel. This avoids repeating similar data.
My SQL statement is this:
$query = mysql_query("SELECT * FROM Reservations WHERE Date = '$DateToday' ORDER BY Airline ASC, Flight ASC, Name");
but I guess to achieve the desired display php would be more relevant than MySQL.
So first the while loop....
while ($row = mysql_fetch_array($query)) { $results = mysql_query("SELECT * FROM Reservations WHERE Airline = '$Airline'");
$Count = mysql_num_rows($results);
if($Count > 1) // More then 1 passenger on same flight
{
$iReservationID = $row['ReservationID'];
$iAirline = strtoupper($row['Airline']);
$iFlight = strtoupper($row['Flight']);
$iName = strtoupper($row['Name']);
$iName = "<BR>".$iName;
} else {// NOT More then 1 passenger on same flight
$ReservationID = $row['ReservationID'];
$Airline = strtoupper($row['Airline']);
$Flight = strtoupper($row['Flight']);
$Name = strtoupper($row['Name']);
}
}
<table>
<tr>
<td>AIRLINE</td>";
<td>FLIGHT#</td>";
<td>PASSENGER</td>";
</tr>
<tr>
<td>echo $Airline;</td>
<td>echo $Flight;</td>
<td>print "$Name<BR>$iName</td>
</tr>
</table>
The table works fine with rows for each entry when there is only one passenger but it is duplicating the passenger names when nested.
SELECT DISTINCT doesn't do the trick either nor SELECT FROM Reservations WHERE ReservationID <> $ReservationID - I have tried a second WHILE loop to refetch the data according to FLIGHT# but still not correct.
Suggestions greatly appreciated.

You can try this code
<?php
$query = mysql_query("SELECT *,GROUP_CONCAT(Name SEPARATOR '<BR>') AS PasName FROM Reservations WHERE Date = '$DateToday' GROUP BY Airline,Flight ORDER BY Airline ASC, Flight ASC, Name");
echo "<table>
<tr>
<td>AIRLINE</td>
<td>FLIGHT#</td>
<td>PASSENGER</td>
</tr>";
while ($row = mysql_fetch_array($query)) {
//$results = mysql_query("SELECT * FROM Reservations WHERE Airline = '$Airline'");
$ReservationID = $row['ReservationID'];
$Airline = strtoupper($row['Airline']);
$Flight = strtoupper($row['Flight']);
$Name = strtoupper($row['PasName']);
//$Count = mysql_num_rows($results);
/*if ($Count > 1) { // More then 1 passenger on same flight
$iName = "";
while ($inrow = mysql_fetch_array($results)) {
$iName .= "<BR>".$inrow['Name'];
}
} else {// NOT More then 1 passenger on same flight
// $ReservationID = $row['ReservationID'];
// $Airline = strtoupper($row['Airline']);
// $Flight = strtoupper($row['Flight']);
}*/
echo "<tr>
<td>$Airline</td>
<td>$Flight</td>
<td>$Name</td>
</tr>";
}
echo "</table>";
?>
But, I recommend you to fetch the multiple users within query only i.e replace this query
SELECT * FROM Reservations WHERE Airline = '$Airline'
with
SELECT GROUP_CONCAT(Name SEPARATOR '<BR>') FROM Reservations WHERE Airline = '$Airline' GROUP BY Airline,Flight
so that there is no need of inside loop for concating user names

Try this
$sql = "SELECT * FROM Reservations WHERE Date = '$DateToday' ORDER BY Airline ASC, Flight ASC, Name";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
echo "<table>
<tr>
<td>AIRLINE</td>
<td>FLIGHT#</td>
<td>PASSENGER</td>
</tr>
";
while($row = mysqli_fetch_assoc($result)) {
echo "<tr>
<td>"+$row['ReservationID']+"</td>
<td>"+strtoupper($row['Airline'])+"</td>
<td>"+strtoupper($row['Flight'])+"</td>
<td>"+MethodToFetchNameOfPassengersOfTheFlight(params)+"</td>
</tr>";
echo "</table>";
}
for the method
string MethodToFetchNameOfPassengersOfTheFlight(params){
//write a query to fetch the name of the passenger of the flight
$CustomerNames = "";
//in for each loop do this
foreach($name in $names)
$CustomerNames += $name + "<br>";
return strtoupper($CustomerNames);
}
First we show the details of the airlines. Then we find the passengers of the corresponding flight and append them in a string with breaks and then distplay them.

Related

The first html row is not being displayed

So, let’s say I have 10 rows in my database. However, after the mysql query, only 9 rows are being displayed in the html table.
I need every row from the database to be displayed in the html table.
I hope someone can point me in the right direction. I’ll be here if I need to provide anymore details.
This is my code:
<?php
$sqlQuery = "SELECT * FROM periods";
$result = mysqli_query($conn, $sqlQuery);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$id = $row['id'];
$out = $row['fell_out'];
$in = $row['fell_in'];
$sum = $row['sum'];
$nextEstimate = $row['next_estimate'];
$nextEstimateDays = $row['next_estimate_days'];
$notes = $row['notes'];
$sqlQueryLastDate = "SELECT * FROM (select * from periods WHERE id < $id ORDER BY id DESC LIMIT 1) AS x ORDER BY id LIMIT 1";
$resultLastDate = mysqli_query($conn, $sqlQueryLastDate);
$resultCheckLastDate = mysqli_num_rows($resultLastDate);
if ($resultCheckLastDate > 0) {
while ($rowLastDate = mysqli_fetch_assoc($resultLastDate)) {
$lastInDate = $rowLastDate['fell_in'];
$sqlQueryCurrentDate = "SELECT * FROM (select * from periods WHERE id = $id ORDER BY id DESC LIMIT 1) AS x ORDER BY id LIMIT 1";
$resultCurrentDate = mysqli_query($conn, $sqlQueryCurrentDate);
$resultCheckCurrentDate = mysqli_num_rows($resultCurrentDate);
if ($resultCheckCurrentDate > 0) {
while ($rowCurrentDate = mysqli_fetch_assoc($resultCurrentDate)) {
$currentOutDate = $rowCurrentDate['fell_out'];
$lastIn = new DateTime($lastInDate);
$currentOut = new DateTime($currentOutDate);
$intervalLastCurrent = $lastIn->diff($currentOut);
$elapsedLastCurrent = $intervalLastCurrent->format('%a days %h hours');
/*Why? Php is erasing everything after adding the above variable to the table...Entire first row gets erased!*/
echo "
<tr>
<td>".$id."</td>
<td class='test'>".$elapsedLastCurrent."</td>
<td class='dateOutResult'>".$out."</td>
<td class='dateInResult'>".$in."</td>
<td class='sumHours'>".$sum."</td>
<td class='nextEstimate'>".$nextEstimate." (".$nextEstimateDays.")</td>
<td class='notes'>".$notes."</td>
</tr>";
} /*$sqlQueryCurrentDate*/
}
} /*$sqlQueryLastDate*/
}
} /*$sqlQuery*/
}
?>
Here's the live result: https://unidrones.co.za/periods
I am really new to mysql/php so I do not understand what I'm doing wrong. The nested queries is probably not the best approach to use, but I'm still learning, and any input will be deeply appreciated.
This is because your query is
//select * from periods WHERE id < $id ORDER BY id DESC LIMIT 1;
your first $id will be always equal id.

Pass id's to url on a count being diplayed in table

I have a function in which I am returning a count which when displayed is clickable. When clicked on this count the page redirects to listing of the of users with their details. The count displayed has link to the information page with id's of the users passed in URL. I am not getting the result as the link shows only one user id instead of two(as per database) or some irrelevant id's. Where I am missing the thing, any help will be highly appreciated.
function for displaying count,
function clearedmodule()
{
$id= '';
$res = mysql_query("SELECT id from tbl_users WHERE status= 1 AND type = 3 ");
while($row = mysql_fetch_array($res))
{
$query = mysql_query("SELECT DISTINCT user_id FROM tbl_user_quiz GROUP BY user_id HAVING COUNT(DISTINCT module_id) = '".$this->userQuestionModules()."' AND SUM(cleared) = 0 ");
while($row1 = mysql_fetch_assoc($query))
{
foreach($row1 as $cname => $id)
{
$id .= $row['id'].',';
}
}
}
return substr($id, 0, -1);
}
Now the <td> where the count is being displayed,
<td>Not Cleared</td>
<td>
<?php
$ids = $rep->clearedmodule();
$ids = explode(",",$ids) ;
$linkId = $rep->clearedmodule();
if($linkId)
{ ?>
<?php echo count($ids); ?>
<?php
}
else{
echo "0";
}
?> </a></td>
Using above, the URL I am getting is
reportNotCleared.php?Userid=10131183 where 1013 is right id , 1183 is not at all correct and I want them to be comma separated.
Your second query is the only query you needed. Just remove all the loops except the middle one and you should be good to go!
function clearedmodule() {
$query = mysql_query("SELECT DISTINCT user_id FROM tbl_user_quiz GROUP BY user_id HAVING COUNT(DISTINCT module_id) = '".$this->userQuestionModules()."' AND SUM(cleared) = 0 ");
while($row1 = mysql_fetch_assoc($query)){
$id .= $row1['user_id'] . ',';
}
return substr($id, 0, -1);
}

Sort data which is displayed in a HTML tabled echoed in PHP

I'm still learning PHP & MySQL and the following has confused me for a long time and I'm looking for some guidance as to how I'd be able to do this.
Basically, I have a HTML table which is displayed by an echo which grabs the values from a MySQL database, the table displays Position, User, Today. Weekly & Monthly. The rows that the table displays is dependent on how many users are logged in so if 10 people are logged in, 10 rows will be displayed, 5 users = 5 rows etc. To achieve this I created a loop which displays the information for each logged in user and this is where I think the issue starts with sorting the data. This is what is used to display the data:
<?php
$counter = 1;
include_once 'config.php';
$sql = "SELECT * FROM vicidial_live_agents";
$result = $conn->query($sql);
while($row = $result->fetch_assoc())
{
$dateNow = date('Y-m-d H:i:s');
$dateNow = strtotime($dateNow);
$dateOld = $row['last_state_change'];
$dateOld = strtotime($dateOld);
$dateDiff = $dateNow - $dateOld;
if ($row['status'] == "INCALL") {
$colour = "w3-green";
}
elseif ($row['status'] == "READY") {
$colour = "w3-yellow";
}
elseif ($row['status'] == "PAUSED") {
$colour = "w3-grey";
}
elseif ($row['status'] == "DEAD") {
$colour = "w3-red";
}
$user = $row['user'];
echo
'<tr class="'.$colour.'">
<td class="w3-xlarge">'.$counter.'</td>
<td class="w3-xlarge">'.$user.'</td>';
$sql2 = "SELECT count(status) AS sales FROM vicidial_agent_log WHERE user = '$user' AND DATE(event_time) = CURDATE() AND status = 'SALE'";
$result2 = $conn->query($sql2);
while($row2 = $result2->fetch_assoc())
{
echo
'<td class="w3-xlarge">'.$row2['sales'].'</td>';
$sql3 = "SELECT count(status) AS salesWeek FROM vicidial_agent_log WHERE user = '$user' AND WEEK(event_time) = WEEK(CURDATE()) AND YEAR(event_time) = YEAR(CURDATE()) AND status = 'SALE'";
$result3 = $conn->query($sql3);
while($row3 = $result3->fetch_assoc())
{
echo
'<td class="w3-xlarge">'.$row3['salesWeek'].'</td>';
$sql4 = "SELECT count(status) AS salesMonth FROM vicidial_agent_log WHERE user = '$user' AND MONTH(event_time) = MONTH(CURDATE()) AND YEAR(event_time) = YEAR(CURDATE()) AND status = 'SALE'";
$result4 = $conn->query($sql4);
while($row4 = $result4->fetch_assoc())
{
echo
'<td class="w3-xlarge">'.$row4['salesMonth'].'</td>
</tr>';
$counter++;
}
}
}
}
?>
What I want is for the table to be sorted by highest monthly sales with the highest being at the top and lowest at the bottom.
I have done some research and the solutions I've found I could not get to work with this situation for example, a JS sort from W3Schools wouldn't work and I think this is due to the values being called from the database.
I hope this is clear, any advice on how to tackle this is appreciated :)

Displaying based on Results in Mysql Query

I have an orders table in mysql and in that for some orders I set particular order status like 'review'.
I want to setup a way if any order placed by a particular customer(first and last name) for whom i have previously set order status as 'review' to display a warning in the list.
$sql = "select * from order where firstname = ".$firstname." AND lastname = ".$lastname." AND order_status = 'review';";
$SQLresult = mysql_query("$sql", $DBcon_MySQL);
while($row = mysql_fetch_array($SQLresult)) {
foreach($row as $row){
$result = "warning!";
echo $result;
}
}
The above code does not display anything. please let me know how to fix this.
[EDIT After Applying Answer]
This is how i am using it.
<td width="200">
<?
$sql = "select * from cust_order where firstname = '$firstname' AND lastname = '$lastname' AND order_status = 'review'";
$SQLResult = mysql_query("$sql", $DBcon_MySQL);
while($row = mysql_fetch_array($SQLResult )) {
//$result;
foreach($row as $row ){
//$result="";
$result = "Warning!";
}
?>
<p><? echo $result;?></p>
<?} ?>
</td>
How should i insert a check that it should display warning only once No matter how many orders from single customer are marked as review, display warning only once?
try this,
$sql = "SELECT
*
FROM
`order`
WHERE
firstname = '$firstname' AND lastname = '$lastname' AND
order_status = 'review' LIMIT 1";
$SQLresult = mysql_query($sql, $DBcon_MySQL);
while($row = mysql_fetch_array($SQLresult)) {
foreach($row as $row){
$result = "warning!";
echo $result;
}
}
Please be informed that mysql functions are deprecated and not recommended. USE MySQLi or PDO instead. have a reference from following queries.
http://php.net/manual/en/book.mysqli.php
http://php.net/manual/en/book.pdo.php

select fields and group them in a category in php and mysql

i have a table with staff_id and subjects, i want to display all staffs according to their subjects.
my table
result i want
Physics
-001
-004
-006
Chemistry
-002
-009
Biology
-003
-008
Mathematics
-005
My code
$q = mysql_query("Select staff_id from my_table");
while($row = mysql_fetch_array($q)){
echo $subject .'</br>';
echo $staff_id.'</br>';
}
but this doesn't give the result i want.
any help?
What you need is ORDER BY.
Change your query to:
SELECT STAFF_ID, SUBJECT FROM my_table ORDER BY SUBJECT, STAFF_ID
So you get the records in the right order to work with them.
Something like this?
$q = mysql_query("SELECT `staff_id`, `subject` FROM `my_table`;");
$data = array();
while($row = mysql_fetch_array($q)){
$data[$row['subject']][] = '-'.$row['staff_id'];
}
print_r($data);
Or to echo out the rows
foreach($data as $heading => $rows){
echo $heading.'<br>';
foreach($rows as $row){
echo $row.'<br>';
}
}
You can write your code like this below:
$q = mysql_query("SELECT * FROM my_table ORDER BY SUBJECT, STAFF_ID");
while($row = mysql_fetch_array($q)){
//Do staff
}
The following code should help. You should split each subject into a separate array within your query. Once your query is complete, you should iterate through the subject array, and then within each staff id.
$subjects = array();
$q = mysql_query("Select staff_id from my_table");
while($row = mysql_fetch_array($q)){
if ($subjects[$row['SUBJECT']] == nil) {
$subjects[$row['SUBJECT']] = array();
}
array_push($subjects[$row['SUBJECT']], $row['STAFF_ID']);
}
foreach ($subjects as $key=>$value) {
echo $key . '<br>;
foreach ($vaue as &$staff) {
echo $staff . '<br>';
}
}
$result=mysql_query("SELECT * from table GROUP BY subject");
while($ext=mysql_fetch_object($result)) {
$query=mysql_query(" SELECT * from table WHERE subject='".$ext->subject."'");
echo $ext->subject;
while($res=mysql_fetch_object($query)) {
echo $res->staff_id;
}
}

Categories