PHP Timetable Issue - While Loop Issue - php

I'm making a simple PHP timetabling website. I've made a table and I have the times in a horizontal header and just Monday at the moment but i want to add 5 days, Monday to Friday. I'm just unsure of how to put the correct data in the correct times and day.
My database has id, name, startTime, endTime and Day
Some data could be 0, Basketball, 9:15, 10:15, Mon.
1, Tennis, 10:15, 11:15, Mon.
2, Cricket, 11:15, 12:15 Tue.
I currently have a while loop that can fill in the table, but not in the
correct slots (td).
Here is my table code so far:
<?php
$host = 'localhost';
$user = 'root';
$pass = '******';
$db = 'test';
$error = 'Error Connecting to database';
$error1 = 'Error Selecting to database';
$connect = mysql_connect($host,$user,$pass) or die($error);
$select_db = mysql_select_db($db) or die($error1);
?>
<table border="1px">
<tr>
<div class="differentLine">
<th > </th>
<th > 9:15 - 10:15 </th>
<th > 10:15 - 11:15 </th>
<th > 11:15 - 12:15 </th>
<th > 12:15 - 13:15 </th>
<th > 13:15 - 14:15 </th>
<th > 14:15 - 15:15 </th>
<th > 15:15 - 16:15 </th>
<th > 16:15 - 17:15 </th>
<th > 17:15 - 18:15 </th>
</div>
</tr >
<tr>
<th >Monday </th>
<?php
$sqlip = "Select * From Modules";
$query = mysql_query($sqlip) or die("Error");
while($row = mysql_fetch_array($query))
{
$name = $row['Name'];
$day = $row['Day'];
$start_time = $row['Start_Time'];
$End_Time = $row['End_Time'];
if($start_time == "9:15"){
echo"<td> $name2</td>";
} else {
echo"<td> </td>";
}
if($start_time == "10:15"){
echo"<td> $name2</td>";
} else {
echo"<td> </td>";
}
if($start_time == "11:15"){
echo"<td> $name2</td>";
} else {
echo"<td> </td>";
}
if($start_time == "12:15"){
echo"<td> $name2</td>";
} else {
echo"<td> </td>";
}
if($start_time == "13:15"){
echo"<td> $name2</td>";
} else {
echo"<td> </td>";
}
if($start_time == "14:15"){
echo"<td> $name2</td>";
} else {
echo"<td> </td>";
}
if($start_time == "15:15"){
echo"<td> $name2</td>";
} else {
echo"<td> </td>";
}
if($start_time == "16:15"){
echo"<td> $name2</td>";
} else {
echo"<td> </td>";
}
if($start_time == "17:15"){
echo"<td> $name2</td>";
} else {
echo"<td> </td>";
}
echo "</tr>";
}
?>

There are couple of things.
Why do you have
<tr>
<th >Monday </th>
this isn't being database fed, you need to automate that and put it on a
if you want to dynamically print
1, Tennis, 10:15, 11:15, Mon.
you need to have html aligned this way.
<tr><th><?=$order?>,</th> <th><?=$sports?>,</th><th><?=$timing?></th><th><?=$day?></th></tr>
You should also use switch and case statements instead of if statements to take up less code.
You also have $name2 which is printing a variable which doesn't have any value assigned to it; maybe you want to use $name instead to match up the td's, it looks like $name has a value of $row['Name'] in your code.

Don't use mysql_ function, its insecured and deprecated, use mysqli or pdo instead
In addition, all this code can change to 3 rows:
$times_array = array("9:15","11:15","12:15","13:15","14:15","15:15","16:15","17:15")
$row = in_array($start_time,$times_array)?$name2:"";
echo "<td>".$row."</td>";
========================
if($start_time == "9:15"){
echo"<td> $name2</td>";
} else {
echo"<td> </td>";
}
if($start_time == "10:15"){
echo"<td> $name2</td>";
} else {
echo"<td> </td>";
}
if($start_time == "11:15"){
echo"<td> $name2</td>";
} else {
echo"<td> </td>";
}
if($start_time == "12:15"){
echo"<td> $name2</td>";
} else {
echo"<td> </td>";
}
if($start_time == "13:15"){
echo"<td> $name2</td>";
} else {
echo"<td> </td>";
}
if($start_time == "14:15"){
echo"<td> $name2</td>";
} else {
echo"<td> </td>";
}
if($start_time == "15:15"){
echo"<td> $name2</td>";
} else {
echo"<td> </td>";
}
if($start_time == "16:15"){
echo"<td> $name2</td>";
} else {
echo"<td> </td>";
}
if($start_time == "17:15"){
echo"<td> $name2</td>";
} else {
echo"<td> </td>";
}

Calendars/timetables are easily created in php when using arrays and loops. Here is how I would do it.
First, create the array and times-
//an array of all your start/end times
$times = array(
array('start'=>'9:15', 'end'=>'10:15'),
array('start'=>'10:15', 'end'=>'11:15'),
array('start'=>'11:15', 'end'=>'12:15'),
array('start'=>'12:15', 'end'=>'13:15'),
array('start'=>'13:15', 'end'=>'14:15'),
array('start'=>'14:15', 'end'=>'15:15'),
array('start'=>'15:15', 'end'=>'16:15'),
array('start'=>'16:15', 'end'=>'17:15'),
array('start'=>'17:15', 'end'=>'18:15')
);
Now you can build your header using a loop-
<table border="1px">
<tr class="differentLine">
<th > </th>
<?php foreach($times as $time){
echo '<th > '.$time['start'].' - '.$time['end'].' </th>';
} ?>
</tr >
Second, create an array of the days-
//use the short version (Mon, Tue, etc) as keys, as that is what you show in your data
//and use the long version for displaying
$days = array('Mon'=>'Monday', 'Tue'=>'Tuesday', 'Wed'=>'Wednesday', 'Thu'=>'Thursday', 'Fri'=>'Friday');
Now you can build your rows using a loop-
<?php foreach($days as $short=>$long){ ?>
<tr>
<th > <?php echo $long; ?> </th>
</tr>
<?php } ?>
Third, create an array of your database data-
// order your database data by the Day and Start_Time
<?php
$sqlip = "Select * From Modules ORDER BY Day, Start_Time";
$query = mysql_query($sqlip) or die("Error");
// create an array to hold your data
$events = array();
// loop through your database rows and add to the array
while($row = mysql_fetch_array($query)){
//add the row to the array, using the Day as a key and the Start_time as a key
$events[$row['Day']][$row['Start_Time']] = $row;
}
Now you have an array that would look like-
$events = array(
'Mon'=> array(
'9:15' => array('id'=>0, 'name'=>'Basketball', 'startTime'=>'9:15', 'endTime'=>'10:15', 'Day'=>'Mon'),
'10:15' => array('id'=>1, 'name'=>'Tennis', 'startTime'=>'10:15', 'endTime'=>'11:15', 'Day'=>'Mon')
),
'Tue'=> array(
'11:15' => array('id'=>2, 'name'=>'Cricket', 'startTime'=>'11:15', 'endTime'=>'12:15', 'Day'=>'Wed')
)
);
Fourth, now in your day row loop, loop through each time array, and check if an event array exists-
<?php foreach($days as $short=>$long){ ?>
<tr>
<th > <?php echo $long; ?> </th>
<?php
// check if there are any events for this day
if(isset($events[$short])){
//since there are events for this day, loop through all the times
foreach($times as $k=>$time){
//check if there is an event at this time
if(isset($events[$short][$time['start']])){
//echo the event
echo '<td>'.$events[$short][$time['start']]['name'].'</td>';
}
else {
//since no event, echo blank cell
echo '<td></td>';
}
}
}
else {
// since no events for the day, create blank cells for each time
for($t=0;$t<count($times);$t++){
echo '<td></td>';
}
} ?>
</tr>';
<?php } ?>
Now when you put it all together it would look like -
<?php
//your database connection
...
//
//an array of all your start/end times
$times = array(
array('start'=>'9:15', 'end'=>'10:15'),
array('start'=>'10:15', 'end'=>'11:15'),
array('start'=>'11:15', 'end'=>'12:15'),
array('start'=>'12:15', 'end'=>'13:15'),
array('start'=>'13:15', 'end'=>'14:15'),
array('start'=>'14:15', 'end'=>'15:15'),
array('start'=>'15:15', 'end'=>'16:15'),
array('start'=>'16:15', 'end'=>'17:15'),
array('start'=>'17:15', 'end'=>'18:15')
);
//use the short version (Mon, Tue, etc) as keys, as that is what you show in your data
//and use the long version for displaying
$days = array('Mon'=>'Monday', 'Tue'=>'Tuesday', 'Wed'=>'Wednesday', 'Thu'=>'Thursday', 'Fri'=>'Friday');
// order your database data by the Day and Start_Time
<?php
$sqlip = "Select * From Modules ORDER BY Day, Start_Time";
$query = mysql_query($sqlip) or die("Error");
// create an array to hold your data
$events = array();
// loop through your database rows and add to the array
while($row = mysql_fetch_array($query)){
//add the row to the array, using the Day as a key and the Start_time as a key
$events[$row['Day']][$row['Start_Time']] = $row;
} ?>
<table border="1px">
<tr class="differentLine">
<th > </th>
<?php foreach($times as $time){
echo '<th > '.$time['start'].' - '.$time['end'].' </th>';
} ?>
</tr >
<?php foreach($days as $short=>$long){ ?>
<tr>
<th > <?php echo $long; ?> </th>
<?php
// check if there are any events for this day
if(isset($events[$short])){
//since there are events for this day, loop through all the times
foreach($times as $k=>$time){
//check if there is an event at this time
if(isset($events[$short][$time['start']])){
//echo the event
echo '<td>'.$events[$short][$time['start']]['name'].'</td>';
}
else {
//since no event, echo blank cell
echo '<td></td>';
}
}
}
else {
// since no events for the day, create blank cells for each time
for($t=0;$t<count($times);$t++){
echo '<td></td>';
}
} ?>
</tr>';
<?php } ?>

Related

Unable to show row and columns dynamically using rowspan in php

I'm trying to show booking using tables, which have dynamic rows and also rowspan.
Here is my code:
<table border="1" style='width: 100%' >
<tr>
<th style='background-color:green;width: 80px' ><font color="white">Time</font></th>
<?php
$i=1;
while($i<=$no_court)
{
echo "<th style='background-color:green;width: 80px'> <font color='white'>Court".$i."</font></th>";
$i+=1;
}
?>
</tr>
<tr>
<td>8:00 AM</td>
<?php
$i=1;
while($i<=$no_court)
{
$flag=0;
$j=0;
while(sizeof($start) > $j )
{
$start_time=$start[$j];
$finish_time=$finish[$j];
$court=$court1[$j];
$sst = strtotime($start_time);
$eet= strtotime($finish_time);
$diff= $eet-$sst;
$timeElapsed= gmdate("h:i",$diff);
$timeElapsed+=1;
if ($start_time=='08:00:00' && $court==$i)
{
$fio_time=$finish[$j];
if($fio_time=='13:00:00')
{
$f_time='1:00:00';
}
$f=$facility_id[$j];
$sql15 = $dbConnection->prepare('SELECT * FROM tbl_facility WHERE facility_id=?');
$sql15->execute(array($f));
$row15 = $sql15->fetch();
$facility_name=$row15['facility_name'];
if($block_by[$j]=="1")
{
echo "<td style='background-color:blue;' rowspan='$timeElapsed'>
<font size='2' color='white'><b><center>$league[$j]</b></br>
Reserved </br>
$facility_name</br>
$start_time-$f_time</br>
<a href='' onClick='javascript: openPopup($id[$j])' style='color:white;'>Edit</a>
<a href='delete.php?id=$id[$j]' style='color:white;' onclick='return confirmdelete()' >Delete</a>
</center></font></td>";
break;
}
elseif($block_by[$j]=="2")
{
$p=$player_id[$j];
$sql17 = $dbConnection->prepare('SELECT * FROM tbl_player_registration WHERE player_id=?');
$sql17->execute(array($p));
$row17 = $sql17->fetch();
$first_name=$row17['first_name'];
echo "<td style='background-color:gray;' rowspan='$timeElapsed'>
<font size='2' color='white'><b><center>Reserved By</b></br>
$first_name </br>
</center></font></td>";
break;
}
}
elseif($start_time <='08:00:00' && $finish_time >='08:00:00' && $court==$i )
{
break;
}
elseif($court==$i )
{
$l=0;
while(sizeof($court) > $l)
{
$ta=$start[$l];
$fa=$finish[$l];
$ca=$court1[$l];
if($ta >='08:00:00' && $fa <='08:00:00' && $ca==$i )
{
$flag=1;$court=$ca;
}
$l+=1;
}
}
$j+=1;
}
if($flag==1 )
{
echo "<td></td>";
}
if($flag==0 )
{
}
if($court != $i)
{
echo "<td></td>";
}
$i+=1;
}
?>
</tr>
</table>
Its showing output as this image:
Its showing data properly but adding an extra column, which make the table look disturbing.
I want to show the result as this image:
I'm little confused where I'm messing the code. Kindly help to sort this issue.

While loop and array in php

I have a while loop that will loop for 2 times (Monday and Tuesday).
Within the while loop I have a condition to check whether the first looped is "Monday", if is Monday it will check for the value and checked the corresponding checkbox.
The code work perfectly for Monday. But checkboxes of Tuesday is not echo at all.
<div class="form-group">
<table>
<tr>
<td style="width: 10%"> </td>
<?php
//Get the list of time
$sqlTime="SELECT timeDesc FROM time";
$resultTime=mysql_query($sqlTime);
while($rowTime=mysql_fetch_array($resultTime))
{
?>
<td style="text-align: center"><?php echo $rowTime['timeDesc'];?></td>
<?php
}
?>
</tr>
<?php
//Get the list of day
$sqlDay="SELECT dayDesc FROM day";
$resultDay=mysql_query($sqlDay);
while($rowDay=mysql_fetch_array($resultDay))
{
?>
<tr>
<td><?php echo $rowDay['dayDesc'];?></td>
<?php
//Get the list of time
$sqlTime="SELECT * FROM time";
$resultTime=mysql_query($sqlTime);
while($rowTime=mysql_fetch_array($resultTime))
{
if($rowDay['dayDesc'] == 'Monday')
{
//Get tutor preferences for Monday
$sqlGetMonday = mysql_query("SELECT tutorPreferencesMon FROM tutorpreferences WHERE tutorID='$showTutorID'");
$resultGetMonday = mysql_fetch_array($sqlGetMonday);
$tutorGetMonday = $resultGetMonday['tutorPreferencesMon'];
$showMonday = $tutorGetMonday;
$mondayArray = explode(',', $showMonday);
while($rowTimeList=mysql_fetch_array($resultTimeList))
{
$checkedMonday = "";
foreach($mondayArray as $monday_Array)
{
if($monday_Array == $rowTimeList['timeID'])
{
$checkedMonday = "checked";
}
}
echo "<td style='text-align: center'><input type='checkbox' name='".$rowDay['dayDesc']."[]' value='".$rowTimeList['timeID']."' ".$checkedMonday."></td>";
}
}//End if Monday
elseif($rowDay['dayDesc'] == 'Tuesday')
{
//Get tutor preferences for Tuesday
$sqlGetTuesday = mysql_query("SELECT tutorPreferencesTues FROM tutorpreferences WHERE tutorID='$showTutorID'");
$resultGetTuesday = mysql_fetch_array($sqlGetTuesday);
$tutorGetTuesday = $resultGetTuesday['tutorPreferencesTues'];
$showTuesday = $tutorGetTuesday;
$tuesdayArray = explode(',', $showTuesday);
while($rowTimeList=mysql_fetch_array($resultTimeList))
{
$checkedTuesday = "";
foreach($tuesdayArray as $tuesday_Array)
{
if($tuesday_Array == $rowTimeList['timeID'])
{
$checkedTuesday = "checked";
}
}
echo "<td style='text-align: center'><input type='checkbox' name='".$rowDay['dayDesc']."[]' value='".$rowTimeList['timeID']."' ".$checkedTuesday."></td>";
}
}//End if Tuesday
elseif($rowDay['dayDesc'] == 'Wednesday')
{
//Get tutor preferences for Wednesday
$sqlGetWednesday = mysql_query("SELECT tutorPreferencesWed FROM tutorpreferences WHERE tutorID='$showTutorID'");
$resultGetWednesday = mysql_fetch_array($sqlGetWednesday);
$tutorGetWednesday = $resultGetWednesday['tutorPreferencesWed'];
$showWednesday = $tutorGetWednesday;
$wednesdayArray = explode(',', $showWednesday);
while($rowTimeList=mysql_fetch_array($resultTimeList))
{
$checkedWednesday = "";
foreach($wednesdayArray as $wednesday_Array)
{
if($wednesday_Array == $rowTimeList['timeID'])
{
$checkedWednesday = "checked";
}
}
echo "<td style='text-align: center'><input type='checkbox' name='".$rowDay['dayDesc']."[]' value='".$rowTimeList['timeID']."' ".$checkedWednesday."></td>";
}
}//End if Wednesday
elseif($rowDay['dayDesc'] == 'Thursday')
{
//Get tutor preferences for Thursday
$sqlGetThursday = mysql_query("SELECT tutorPreferencesThurs FROM tutorpreferences WHERE tutorID='$showTutorID'");
$resultGetThursday = mysql_fetch_array($sqlGetThursday);
$tutorGetThursday = $resultGetThursday['tutorPreferencesThurs'];
$showThursday = $tutorGetThursday;
$thursdayArray = explode(',', $showThursday);
while($rowTimeList=mysql_fetch_array($resultTimeList))
{
$checkedThursday = "";
foreach($thursdayArray as $thursday_Array)
{
if($thursday_Array == $rowTimeList['timeID'])
{
$checkedThursday = "checked";
}
}
echo "<td style='text-align: center'><input type='checkbox' name='".$rowDay['dayDesc']."[]' value='".$rowTimeList['timeID']."' ".$checkedThursday."></td>";
}
}//End if Thursday
elseif($rowDay['dayDesc'] == 'Friday')
{
//Get tutor preferences for Friday
$sqlGetFriday = mysql_query("SELECT tutorPreferencesFri FROM tutorpreferences WHERE tutorID='$showTutorID'");
$resultGetFriday = mysql_fetch_array($sqlGetFriday);
$tutorGetFriday = $resultGetFriday['tutorPreferencesFri'];
$showFriday = $tutorGetFriday;
$fridayArray = explode(',', $showFriday);
while($rowTimeList=mysql_fetch_array($resultTimeList))
{
$checkedFriday = "";
foreach($fridayArray as $friday_Array)
{
if($friday_Array == $rowTimeList['timeID'])
{
$checkedFriday = "checked";
}
}
echo "<td style='text-align: center'><input type='checkbox' name='".$rowDay['dayDesc']."[]' value='".$rowTimeList['timeID']."' ".$checkedFriday."></td>";
}
}//End if Friday
elseif($rowDay['dayDesc'] == 'Saturday')
{
//Get tutor preferences for Saturday
$sqlGetSaturday = mysql_query("SELECT tutorPreferencesSat FROM tutorpreferences WHERE tutorID='$showTutorID'");
$resultGetSaturday = mysql_fetch_array($sqlGetSaturday);
$tutorGetSaturday = $resultGetSaturday['tutorPreferencesSat'];
$showSaturday = $tutorGetSaturday;
$saturdayArray = explode(',', $showSaturday);
while($rowTimeList=mysql_fetch_array($resultTimeList))
{
$checkedSaturday = "";
foreach($saturdayArray as $saturday_Array)
{
if($saturday_Array == $rowTimeList['timeID'])
{
$checkedSaturday = "checked";
}
}
echo "<td style='text-align: center'><input type='checkbox' name='".$rowDay['dayDesc']."[]' value='".$rowTimeList['timeID']."' ".$checkedSaturday."></td>";
}
}//End if Saturday
elseif($rowDay['dayDesc'] == 'Sunday')
{
//Get tutor preferences for Sunday
$sqlGetSunday = mysql_query("SELECT tutorPreferencesSun FROM tutorpreferences WHERE tutorID='$showTutorID'");
$resultGetSunday = mysql_fetch_array($sqlGetSunday);
$tutorGetSunday = $resultGetSunday['tutorPreferencesSun'];
$showSunday = $tutorGetSunday;
$sundayArray = explode(',', $showSunday);
while($rowTimeList=mysql_fetch_array($resultTimeList))
{
$checkedSunday = "";
foreach($sundayArray as $sunday_Array)
{
if($sunday_Array == $rowTimeList['timeID'])
{
$checkedSunday = "checked";
}
}
echo "<td style='text-align: center'><input type='checkbox' name='".$rowDay['dayDesc']."[]' value='".$rowTimeList['timeID']."' ".$checkedSunday."></td>";
}
}//End if Sunday
}//End while
?>
</tr>
<?php
}
?>
</table>
</div>
Your while loop changes variable $rowTime, while you're checking for the variable $rowDay. You may want to double-check that.
EDIT:
Use this code:
<div class="form-group">
<table>
<tr>
<td style="width: 10%"> </td>
<?php
//Get the list of time
$sqlTime="SELECT timeDesc FROM time";
$resultTime=mysql_query($sqlTime);
while($rowTime=mysql_fetch_array($resultTime))
{
?>
<td style="text-align: center"><?php echo $rowTime['timeDesc'];?></td>
<?php
}
?>
</tr>
<?php
//Get the list of day
$sqlDay="SELECT dayDesc FROM day";
$resultDay=mysql_query($sqlDay);
while($rowDay=mysql_fetch_array($resultDay))
{
?>
<tr>
<td><?php echo $rowDay['dayDesc'];?></td>
<?php
//Get the list of time
$sqlTime="SELECT * FROM time";
$resultTime=mysql_query($sqlTime);
$preferences = array('Monday' => 'tutorPreferencesMon',
'Tuesday' => 'tutorPreferencesTues',
'Wednesday' => 'tutorPreferencesWed',
'Thursday' => 'tutorPreferencesThurs',
'Friday' => 'tutorPreferencesFri',
'Saturday' => 'tutorPreferencesSat',
'Sunday' => 'tutorPreferencesSun');
while($rowTime=mysql_fetch_array($resultTime))
{
$preferences = $preferences[$rowDay['dayDesc']];
$sqlGetMonday = mysql_query("SELECT ".$preferences." FROM tutorpreferences WHERE tutorID='$showTutorID'");
$resultGetMonday = mysql_fetch_array($sqlGetMonday);
$tutorGetMonday = $resultGetMonday[$preferences];
$showMonday = $tutorGetMonday;
$mondayArray = explode(',', $showMonday);
while($rowTimeList=mysql_fetch_array($resultTimeList))
{
$checkedMonday = "";
foreach($mondayArray as $monday_Array)
{
if($monday_Array == $rowTimeList['timeID'])
{
$checkedMonday = "checked";
}
}
echo "<td style='text-align: center'><input type='checkbox' name='".$rowDay['dayDesc']."[]' value='".$rowTimeList['timeID']."' ".$checkedMonday."></td>";
}
}//End while
?>
</tr>
<?php
}
?>
</table>
</div>

Can't make it appear in the correct way PHP

we have an assignment for today in which we have to echo some data of the database. The data is month, case, vehicle_id. In a month there can be many cases and in a case there can be many vehicle_ids. What i have achieve to do is to show it in the following way
month st_case veh_id
1 10001 1000011
1 10002 1000021
1 10002 1000022
2 10058 1000581
using this code:
<table border="1">
<tr>
<th>month</th>
<th>st_case</th>
<th>veh_id</th>
</tr>
<?php
// Loop on rows in the result set.
for($ri = 0; $ri < $numrows; $ri++) {
echo "<tr>\n";
$row = pg_fetch_array($result, $ri);
echo " <td>", $row["month"], "</td>
<td>", $row["st_case"], "</td>
<td>", $row["veh_id"], "</td>
</tr>
";
}
pg_close($link);
?>
</table>
The problem is that what i really want to do is to make it show for each month the cases and for each case the vehicles.
1
10001
1000011
10002
1000021
1000022
2
10058
1000581
I tried to do something like this but it doesn't show correctly. If someone could help me with this i would be really thankfull.
<table border="1">
<tr>
<th>month</th>
<th>st_case</th>
<th>veh_id</th>
</tr>
<?php
// Loop on rows in the result set.
$currentmonth = 0;
for($ri = 0; $ri < $numrows; $ri++)
{
$row = pg_fetch_array($result, $ri);
if ($currentmonth != $row["month"])
{
echo "<tr>";
echo "<td>";
echo "<strong>".$row["month"]."</strong>";
echo "</td>";
echo "</tr>";
}
echo "<tr>";
echo "<td>".$row["st_case"]."</td>";
echo "</tr>";
echo "<tr>";
echo "<td>".$row["veh_id"]."</td>";
echo "</tr>";
$currentmonth = $row["month"];
}
pg_close($link);
?>
</table>
picture: http://i61.tinypic.com/2nb8vgl.png
$ret = pg_fetch_all($result);
$group = array();
foreach($ret as $v){
$group[$v['month']][$v['st_case']][] = $v['veh_id'];
}
foreach($group as $month=>$value){
echo $month."<br/>";
foreach($value as $st_case=>$v){
echo $st_case."<br/>";
foreach($v as $veh_id){
echo $veh_id."<br/>";
}
}
}
PS.then add some css to style your table
If you do not intend to display items in a table, do not use table
What you want is something like this:
<div class="result">
<div class="month_group">
<span class="month bold">1</span>
<div class="case_group">
<span class="case">10001</span>
<div class="veh_group">
<span class="veh_id">1000011</span>
</div>
<span class="case">10002</span>
<div class="veh_group">
<span class="veh_id">1000021</span>
<span class="veh_id">1000022</span>
</div>
</div>
</div>
<div class="month_group">
<span class="month">2</span>
<div class="case_group">
<span class="case">10058</span>
<div class="veh_group">
<span class="veh_id">1000081</span>
</div>
</div>
</div>
</div>
Then all that's left to do is applying simple css to give the classes some padding/margin.
HTML is a markup language. You structure the web page using the HTML tags. However, how it would look like depends more on css (which is why it's called Cascading Style Sheets).
Here's the rendering code. I have not tested it yet, and I have not touched PHP for sometime, but it should give you some general ideas:
echo "<div class=\"result\">";
for($ri = 0; $ri < $numrows; $ri++) {
$row = pg_fetch_array($result, $ri);
$month = $row["month"];
echo "<div class=\"month_group\">\n";
echo "<span class=\"month\">".$month."</span>\n";
echo "<div class=\"case_group\">\n";
for ($ci = $ri; $ci < $numrow; $ci++) {
if ($ci == $ri) {
$c_row = $row;
} else {
$c_row = pg_fetch_array($result, $ci);
}
if ($c_row["month"] != $month) {
// We have moved to another month
break;
}
$case = $c_row["st_case"];
echo "<span class=\"case\">".$case."</span>\n";
echo "<div class=\"veh_group\">\n";
for ($vi = $ci; $vi < $numrow; $vi++) {
if ($vi == $ci) {
$v_row = $c_row;
} else {
$v_row = pg_fetch_array($result, $vi);
}
if ($v_row["st_case"] != $case) {
// We have moved to another case
break;
}
$veh = $v_row["veh_id"];
echo "<span class=\"veh_id\">".$veh."</span>\n";
// we have already processed rows whose indexes are less or equal $vi
$ri = $vi;
}
echo "</div>";
}
echo "</div></div>";
}
Try this updated code
<table border="1">
<tr>
<th>month</th>
<th>st_case</th>
<th>veh_id</th>
</tr>
<?php
// Loop on rows in the result set.
$currentmonth = 0;
for($ri = 0; $ri < $numrows; $ri++)
{
$row = pg_fetch_array($result, $ri);
// Open the row
echo "<tr>";
echo "<td><strong>" . $row["month"] . "</strong></td>"; //open and close each column
echo "<td>".$row["st_case"]."</td>";
echo "<td>".$row["veh_id"]."</td>";
echo "</tr>"; //close the row
$currentmonth = $row["month"];
}
pg_close($link);
?>
</table>
You will also need to call the ORDER BY keyword in your MySQL statement to order by month.
Here is a simple tutorial on how to do this.
Here is a Demo of how it might look in your application.
Let me know if this helps and if i can be of any other help.

call or create session variable in SUM

I am not very familiar with PHP or MySQL, but after researching here I have been able to learn and get very close to what I need and build my first sum query. I am trying to read the database and sum values based on several variables.
I need the reservation_pax from the reservations table where reservation_time is 8:00 where reservation_hidden = 0 and reservation_date is something. I can manually enter the date and it works. I am now trying to use a session code already in the script or find a way to to dynamically add based on selected date.
Here is the code I have working without the dynamic aspect or session.
$result = mysql_query("SELECT SUM(reservation_pax)
FROM reservations
WHERE reservation_time = '8:00:00'
AND reservation_date = '2014-10-27'
AND reservation_hidden ='0'") ;
if ($result === false) {
die(mysql_error()); // TODO: better error handling
}
while($row = mysql_fetch_array($result)) {
echo $row['SUM(reservation_pax)'];
}
Here is the full code of the page where I entered the above addition. Can anyone help me figure out how to call the selected date rather than having to manually enter.
<!-- Begin reservation table data -->
<br/>
<table class="global resv-table-small" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<?php
echo "<td class='noprint'> </td>";
echo "<td>Time</td>";
echo "<td>Guests/Type</td>";
echo "<td>Name</td>";
echo "<td>Special Instructions/Notes</td>";
echo "<td class='noprint'>Table</td>";
echo "<td class='noprint'>Status</td>";
echo "<td class='noprint'>Created</td>";
echo "<td class='noprint'>Details/Delete</td>";
echo "</tr>";
// Clear reservation variable
$reservations ='';
if ($_SESSION['page'] == 1) {
$reservations = querySQL('all_reservations');
}else{
$reservations = querySQL('reservations');
}
// reset total counters
$tablesum = 0;
$guestsum = 0;
if ($reservations) {
//start printing out reservation grid
foreach($reservations as $row) {
// reservation ID
$id = $row->reservation_id;
$_SESSION['reservation_guest_name'] = $row->reservation_guest_name;
// check if reservation is tautologous
$tautologous = querySQL('tautologous');
echo "<tr id='res-".$id."'>";
echo "<td";
// daylight coloring
if ($row->reservation_time > $daylight_evening){
echo " class='evening noprint'";
}else if ($row->reservation_time > $daylight_noon){
echo " class='afternoon noprint'";
}else if ($row->reservation_time < $daylight_noon){
echo " class='morning noprint'";
}
echo " style='width:10px !important; padding:0px;'> </td>";
echo "<td id='tb_time'";
// reservation after maitre message
if ($row->reservation_timestamp > $maitre['maitre_timestamp'] && $maitre['maitre_comment_day']!='') {
echo " class='tautologous' title='"._sentence_13."' ";
}
echo ">";
echo "<strong>".formatTime($row->reservation_time,$general['timeformat'])."</strong></td>";
echo "<td id='tb_pax'><strong class='big'>".$row->reservation_pax."</strong> <span class='noprint'>";
printType($row->reservation_hotelguest_yn);
//echo "<img src='images/icons/user-silhouette.png' class='middle'/>";
echo "</span></td><td style='width:10%' id='tb_name'><span class='noprint'>".printTitle($row->reservation_title)."</span><strong> <a id='detlbuttontrigger' href='ajax/guest_detail.php?id=".$id."'";
// color guest name if tautologous
if($tautologous>1){echo" class='tautologous tipsy' title='"._tautologous_booking."'";}
echo ">".$row->reservation_guest_name."</a></strong>";
// old reservations symbol
if( (strtotime($row->reservation_timestamp) + $general['old_days']*86400) <= time() ){
echo "<img src='images/icons/clock-bolt.png' class='help tipsyold middle smicon' title='"._sentence_11."' />";
}
// recurring symbol
if ($row->repeat_id !=0) {
echo " <img src='images/icons/loop-alt.png' alt='"._recurring.
"' title='"._recurring."' class='tipsy' border='0' >";
}
echo"</td><td style='width:10%' id='tb_note'>";
if ($_SESSION['page'] == 1) {
echo $row->outlet_name;
}else{
echo $row->reservation_notes;
}
echo "</td>";
if($_SESSION['wait'] == 0){
echo "<td class='big tb_nr' style='width:85px;' id='tb_table'><img src='images/icons/table_II.png' class='tipsy leftside noprint' title='"._table."' /><div id='reservation_table-".$id."' class='inlineedit'>".$row->reservation_table."</div></td>";
}
echo "<td class='noprint'><div>";
getStatusList($id, $row->reservation_status);
echo "</div></td>";
echo "<td class='noprint'>";
echo "<small>".$row->reservation_booker_name." | ".humanize($row->reservation_timestamp)."</small>";
echo "</td>";
echo "<td class='noprint'>";
// MOVE BUTTON
// echo "<a href=''><img src='images/icons/arrow.png' alt='move' class='help' title='"._move_reservation_to."'/></a>";
// WAITLIST ALLOW BUTTON
if($_SESSION['wait'] == 1){
$leftspace = leftSpace(substr($row->reservation_time,0,5), $availability);
if($leftspace >= $row->reservation_pax && $_SESSION['outlet_max_tables']-$tbl_availability[substr($row->reservation_time,0,5)] >= 1){
echo" <a href='#' name='".$id."' class='alwbtn'><img src='images/icons/check-alt.png' name='".$id."' alt='"._allow."' class='help' title='"._allow."'/></a> ";
}
}
// EDIT/DETAIL BUTTON
echo "<a href='?p=102&resID=".$id."'><img src='images/icons/pen-fill.png' alt='"._detail."' class='help' title='"._detail."'/></a> ";
// DELETE BUTTON
if ( current_user_can( 'Reservation-Delete' ) && $q!=3 ){
echo"<a href='#modalsecurity' name='".$row->repeat_id."' id='".$id."' class='delbtn'>
<img src='images/icons/delete.png' alt='"._cancelled."' class='help' title='"._delete."'/></a>";
}
echo"</td></tr>";
$tablesum ++;
$guestsum += $row->reservation_pax;
}
}
?>
</tbody>
<tfoot>
<tr style="border:1px #000;">
<td class=" noprint"></td><td></td>
<td colspan="2" class="bold"><?php echo $guestsum;?> <?php echo _guest_summary;?></td>
<td></td>
<td colspan="2" class="bold"><?php echo $tablesum;?> <?php echo _tables_summary;?></td>
<td colspan="2" class="bold"><?php
$result = mysql_query("SELECT SUM(`reservation_pax`) FROM `reservations` WHERE `reservation_time` = '8:00:00' AND `reservation_date` = '{$_SESSION['selectedDate']}' AND `reservation_hidden` ='0'") ;
if($result === FALSE) {
die(mysql_error()); // TODO: better error handling
}
while($row = mysql_fetch_array($result))
{
echo $row['SUM(reservation_pax)'];
}
?>
<?php echo '/ 40 ', _guest_summary, ' -8:00 AM';?></td>
<td></td>
<?php
if($_SESSION['wait'] == 0){
//echo "<td></td>";
}
?>
</tr>
</tfoot>
</table>
<!-- End reservation table data -->
you can use alias field, as:
$result = mysql_query("SELECT SUM(reservation_pax) AS reserve_sum
FROM reservations WHERE reservation_time = '8:00:00'
AND reservation_date = '2014-10-27'
AND reservation_hidden ='0'"
) ;
....
and get access it as:
while($row = mysql_fetch_array($result))
{
echo $row['reserve_sum'];
}
$result = mysql_query("SELECT SUM(reservation_pax) FROM reservations WHERE reservation_time = '8:00:00' AND reservation_date = '{$_SESSION['selectedDate']}' AND reservation_hidden ='0'") ;
if($result === FALSE) {
die(mysql_error()); // TODO: better error handling
}
while($row = mysql_fetch_array($result))
{
echo $row['SUM(reservation_pax)'];
}
?>

How to create a table in HTML using PHP

I have 5 pictures stored in a folder and their links stored on the database.
I want to put them in a table of three columns on each row.
<body>
<center>
<table border='1'>
<?php
$host="";
$username="";
$password="";
$db_name="fruits_db";
$tbl_name="fruits_tbl";
$connection=mysqli_connect("$host","$username","$password","$db_name");
if (mysqli_connect_errno())
{
echo "The application has failed to connect to the mysql database server: " .mysqli_connect_error();
}
$result = mysqli_query($connection, "SELECT * FROM fruits_tbl")or die("Error: " . mysqli_error($connection));
$num_rows=mysqli_num_rows($result);
$rows = $num_rows/3;
for($i=1; $i<=$rows ; $i++)
{
echo "<tr>";
for($j=1; $j<=3; $j++)
{
while($row = mysqli_fetch_array($result))
{
echo
("<td width='180px' height='200px'>"
."<div class = 'fruit_image'>"
."<img src='"
.$row['fruit_image']
."'/>"
."</div>"
."<div class = 'fruit_title'>"
.$row['fruit_name']
."</div>"
."</td>"
);
}
}
echo "</tr>";
}
mysqli_close($connection);
?>
</table>
</center>
</body>
</html>
The above code I created, contains two FOR loops. The script should count the number of rows in the table, and then divide by 3(the number of columns on each row in the HTML table).
I wonder where I'm going wrong wit this code.
With your while($row = mysqli_fetch_array($result)){} inside your 1st for loop it will run through all your rows, before the outside loop runs 2nd/3rd time.
Here is another way to do it -
$counter = 1;
// start 1st row
echo "<tr>";
while($row = mysqli_fetch_array($result)){
// if the 4th cell, end last row, and start new row
if ($counter%3==1){
echo "</tr><tr>";
}
echo
"<td width='180px' height='200px'>"
."<div class = 'fruit_image'>"
."<img src='"
.$row['fruit_image']
."'/>"
."</div>"
."<div class = 'fruit_title'>"
.$row['fruit_name']
."</div>"
."</td>";
// increase the counter
$counter++;
}
// close the last row
echo "</tr>";
You're looping through all the results in the first table cell.
Try something like this instead:
for($i=1; $i<=$rows ; $i++) {
echo "<tr>";
for($j=1; $j<=3; $j++) {
$row = mysqli_fetch_array($result);
if ($row) {
echo(
"<td width='180px' height='200px'>"
."<div class = 'fruit_image'>"
."<img src='"
.$row['fruit_image']
."'/>"
."</div>"
."<div class = 'fruit_title'>"
.$row['fruit_name']
."</div>"
."</td>"
);
}
}
echo "</tr>";
}
If you just want to format the display with a new row after every 3 records, you could use the modulus operator:
$cntr = 0;
echo '<tr>';
while($row = mysqli_fetch_array($result)) {
$cntr++;
echo '
<td width="180px" height="200px">
<div class="fruit_image">
<img src="'.$row['fruit_image'].'" />
</div>
<div class="fruit_title">'.$row['fruit_name'].'</div>
</td>';
if ($cntr % 3 == 0 && $cntr != $num_rows)
echo '</tr><tr>';
}
echo '</tr>';
Keep in mind however that all the solutions presented so far may leave you with a last row with one or two td elements. You can fill this if you desire with empty <td> </td> columns.
print "<center><table border=1>
<tr>
<td>id</td>
<td>name</td>
<td>company</td>
<td>branch</td>
<td>job title</td>
<td>contact</td>
<td>email</td>
<td>mgs</td>
</tr>";
while($row=mysql_fetch_array($query))
{
print "<tr>";
for ($i=0;$i<=(count($row)/2);$i++)
{
print "<td>$row[$i]</td>";
} print"</tr>";
}
}
else{echo " <p>No Records Found</p>";}
<?php
function studentTable($name,$grade){
echo "<tr> <td>$name</td><td>$grade</td></tr>";
}
?>
<table style="width:100%" border="solid">
<tr>
<th>Name</th>
<th>Grade</th>
</tr>
<?php studentTable("Sarah", 90) ?>

Categories