SQL Query only displaying first result rather than arrayed data - php

Basically I am building a calendar page that displays the months, and the days of the month(pulled from my database) and then any days that are inside the "start_date - end_date" variables are displayed with a different cell background color to the days that don't have a start or end date assigned, I have it working to an extent but it's only displaying the earliest of each months record rather than all the results.
ie.
2015-03-12(start) - 2015-03-16(end)
2015-03-03(start) - 2015-03-10(end)
And rather than display like this...
`1 2 [3 4 5 6 7 8 9 10] 11 [12 13 14 15 16] 17 18 19 20 ...`
it's just showing the [3 - 10] record, here is my current code..
<table width="100%" cellspacing="0">
<?php
$cmonth = date('F');
$cyear = date('Y');
$sql = "SELECT * FROM calendar WHERE year = '$cyear' ORDER BY m_order ASC";
$res = mysql_query($sql);
while ($rows = mysql_fetch_array($res)) {
$month_end = $rows['days_in_month'];
$month_name = $rows['month_name'];
$m_order = $rows['m_order'];
$sql2 = "SELECT * FROM trips WHERE start_date LIKE '____-0$m_order-__' ORDER BY start_date ASC";
$res2 = mysql_query($sql2);
$row = mysql_fetch_assoc($res2);
$stdate = $row['start_date'];
$s = date_parse_from_format("Y-m-d", $stdate);
$endate = $row['end_date'];
$e = date_parse_from_format("Y-m-d", $endate);
$start = $s['day'];
$end = $e['day'];
?>
<tr>
<td width="80px"><?php echo $month_name; ?></td>
<?php
foreach(range(1, $month_end) as $days)
{
if(in_array($days, range($start, $end)))
{
echo "<td style=\"background-color: #ccc;\" align=\"center\">" . $days . " </td>";
}
else
echo "<td align=\"center\">" . $days . "</td>";
}
?>
</tr>
<?php } ?>
</table>
Also I am aware of the dangers not using mysqli but I am just learning this on my local machine and plan on researching updated strategies once I get the functions working, so I'll know if my functions are broken or my coding is.
Thanks

try with common function to read data from table
function db_set_recordset($sql) {
$qry = mysql_query($sql);
$row= array();
while($out = mysql_fetch_assoc($qry)) {
$row[] = $out;
}
return $row;
}
$cmonth = date('F');
$cyear = date('Y');
$sql = "SELECT * FROM calendar WHERE year = '$cyear' ORDER BY m_order ASC";
$res = mysql_query($sql);
while ($rows = mysql_fetch_array($res)) {
$month_end = $rows['days_in_month'];
$month_name = $rows['month_name'];
$m_order = $rows['m_order'];
$sql2 = "SELECT * FROM trips WHERE start_date LIKE '____-0$m_order-__' ORDER BY start_date ASC";
$res2 = mysql_query($sql2);
$row = db_set_recordset($res2);
$stdate = $row['start_date'];
$s = date_parse_from_format("Y-m-d", $stdate);
$endate = $row['end_date'];
$e = date_parse_from_format("Y-m-d", $endate);
$start = $s['day'];
$end = $e['day'];
?>
<tr>
<td width="80px"><?php echo $month_name; ?></td>
<?php
foreach(range(1, $month_end) as $days)
{
if(in_array($days, range($start, $end)))
{
echo "<td style=\"background-color: #ccc;\" align=\"center\">" . $days . " </td>";
}
else
echo "<td align=\"center\">" . $days . "</td>";
}
?>
</tr>
<?php } ?>
</table>

You are only fetching one row of your result set from your trips table. You need something like this to get the second one.
while ( $row = mysql_fetch_assoc($res2) ) {
/* process each row */
}
You're doing this right for your other result set. Take a look at the examples here: http://php.net/manual/en/function.mysql-fetch-assoc.php
You'll need to run through the result set rows and accumulate your "hot" days, then render the days just once. Something like this:
$sql2 = "SELECT * FROM trips WHERE start_date LIKE '____-0$m_order-__' ORDER BY start_date ASC";
$res2 = mysql_query($sql2);
while ($row = mysql_fetch_assoc($res2)) {
$stdate = $row['start_date'];
$s = date_parse_from_format("Y-m-d", $stdate);
$endate = $row['end_date'];
$e = date_parse_from_format("Y-m-d", $endate);
$start = $s['day'];
$end = $e['day'];
$hot_days = array();
foreach(range(1, $month_end) as $days) {
$hot_days[$days] = 0;
if(in_array($days, range($start, $end))) {
$hot_days[$days] ++;
}
}
}
/* now you have a $hot_days array with nonzero values for interesting days */
?>
<tr>
<td width="80px"><?php echo $month_name; ?></td>
<?php
foreach(range(1, $month_end) as $day) {
if($hot_days[$day] > 0) {
echo "<td style=\"background-color: #ccc;\" align=\"center\">" . $days . " </td>";
}
else {
echo "<td align=\"center\">" . $days . "</td>";
}
}
?>
</tr>
With respect, I don't have time to debug this.

Related

PHP loop HTML table for each user

I have a PHP loop which draws a table based off a MYSQLi query.
What i would like to do is create this table based on a userid (in my case the column called 'badgeid')
At the moment its creating one table
$sql = "SELECT first_name,last_name,signintime,signouttime FROM `signin_entries` WHERE iscleaner ='YES' AND signindate = curdate()";
$list_visitors_result=mysqli_query($con,$sql);
$count_visitors = mysqli_num_rows($list_visitors_result);
if($count_visitors != 0) {
while($row = mysqli_fetch_array($list_visitors_result)){
$signintime = $row['signintime'];
$signouttime = $row['signouttime'];
$firstname = $row['first_name'];
$lastname = $row['last_name'];
echo " <tr><td>$firstname $lastname</td>
<td>$signintime</td>";
if ($signouttime == ""){
echo "<td>Not Signed Out Yet</td>";
} else {
echo "<td>$signouttime</td>";
}
$timeFirst = strtotime(date("Y/m/d") . " " . $signintime);
$timeSecond = strtotime(date("Y/m/d") ." " . $signouttime);
//below checks if th second time is less than the first time than it must be from the day before so add 24 hours eg (signin time 23:30:00 signout time 07:30:30 would be 08:00:30 difference)
if ($timeSecond < $timeFirst)
{
$timeSecond = $timeSecond + 86400;
}
if ($signouttime == ""){
echo "<td>Cleaner Has Not Signed Out Yet</td>";
} else {
$differenceInSeconds = $timeSecond - $timeFirst;
echo "<td class='rowDataSd'>".converttime($differenceInSeconds)."</td>";
}
echo "</tr>";
}
}
//below function converts the seconds difference into hh:mm:ss format to the nearest second
function converttime($seconds) {
$t = round($seconds);
return sprintf('%02d:%02d:%02d', ($t/3600),($t/60%60), $t%60);
}
echo "<tr><th></th><th></th><th></th><th>Total Time Worked</th><tr><td></td><td></td><td></td><td class='totalCol'>Total:</td></tr>";
?>
</table>
</div>
</div>
</div>
</div>
</div>
</section>
</div>
Which is great but i really need a table per 'badgeid'
You could do it like that:
$sql = "SELECT first_name,last_name,signintime,signouttime FROM `signin_entries` WHERE iscleaner ='YES' AND signindate = curdate() ORDER BY badgeid ASC";
$list_visitors_result=mysqli_query($con, $sql);
$count_visitors = mysqli_num_rows($list_visitors_result);
if ($count_visitors != 0) {
echo '<table>';
$current_badgeid = '';
while ($row = mysqli_fetch_array($list_visitors_result)) {
if ($current_badgeid == '') {
$current_badgeid = $row['badgeid']; //define if empty, for the first table
}
if($row['badgeid'] != $current_badgeid){
echo '</table><table>';
$current_badgeid = $row['badgeid'];
}
$signintime = $row['signintime'];
$signouttime = $row['signouttime'];
$firstname = $row['first_name'];
$lastname = $row['last_name'];
echo " <tr><td>$firstname $lastname</td><td>$signintime</td>";
if ($signouttime == "") {
echo "<td>Not Signed Out Yet</td>";
} else {
echo "<td>$signouttime</td>";
}
$timeFirst = strtotime(date("Y/m/d") . " " . $signintime);
$timeSecond = strtotime(date("Y/m/d") ." " . $signouttime);
//below checks if th second time is less than the first time than it must be from the day before so add 24 hours eg (signin time 23:30:00 signout time 07:30:30 would be 08:00:30 difference)
if ($timeSecond < $timeFirst) {
$timeSecond = $timeSecond + 86400;
}
if ($signouttime == "") {
echo "<td>Cleaner Has Not Signed Out Yet</td>";
} else {
$differenceInSeconds = $timeSecond - $timeFirst;
echo "<td class='rowDataSd'>".converttime($differenceInSeconds)."</td>";
}
echo "</tr>";
}
echo '</table>';
}
First, you add ORDER BY badgeid ASC to your query. Then you open a table before the loop starts, and you define a $current_badgeid var. Each time the badgeid changes, you close and reopen a table.

PHP : How can get all day between tow date and but it in calender

I have two dates:
10-11-2014 and 17-11-2014
Now i would like to Get all dates between those two.
then i need to check it in calender, If its in calender, I need to color in red color
How can I do that?
This is my calender code :-
<Table class="grayBg" align="center" style="font-family: 'trebuchet MS';font-size:12px" width="288">
<caption style="font-weight:bold;padding-bottom:2px" class="black font10px">
<?php
if(file_exists('winneradmincpanel/connect.php'))
{
require_once('winneradmincpanel/connect.php');
$connect = new connect();
include 'config.php';
require_once('date/hjreedate.php');
$hijri = new HijriCalendar();
include('date/hdate.php');
$date = $hijri -> GregorianToHijri(time());
$hdate = $aday." ".$date[1].' '.$hijri ->monthName($date[0]).' '.$date[2] ." هـ";
/// get current month and year and store them in $cMonth and $cYear variables
(intval($_REQUEST["month"])>0) ? $cMonth = intval($_REQUEST["month"]) : $cMonth = date("m");
(intval($_REQUEST["year"])>0) ? $cYear = intval($_REQUEST["year"]) : $cYear = date("Y");
echo GregorianHijri::getMonthName ( $m,GregorianHijri::$GREGORIAN,$GLOBALS['lang']) . ' ' . $a;
// generate an array with all dates with events
?>
</caption>
<tr style="background:#CCCCCC">
<th>الاثنين</th>
<th>الثلاثاء</th>
<th>الاربعاء</th>
<th>الخميس</th>
<th>الجمعة</th>
<th>السبت</th>
<th>الاحد</th>
</tr>
<?php
$ts = mktime ( 1, 0, 0, $m, 1, $a );
$detail = getdate ( $ts );
echo "<tr>";
if ($detail ['wday'] == 0)
$nb = 6;
else
$nb = $detail ['wday'] - 1;
for($j = 1; $j <= $nb; $j ++)
echo "<td>";
$n = $detail ['wday'];
$valid = TRUE;
$j = 1;
$monthsArray = array();
do {
$valid = checkdate ( $m, $j, $a );
if ($valid) {
//$dateOutput = "$a-$m-$j";
$dateOutput = sprintf ( $GLOBALS['gregorianDateFormat'], $a,$m,$j);
$hijriDay = GregorianHijri::hijriDay($a,$m,$j,$GLOBALS['lang']);
$explod = explode("-",$hijriDay);
$year = $explod[1];
$day = $explod[0];
$hijriDate = GregorianHijri::hijriDate($a,$m,$j,$GLOBALS['lang'],$GLOBALS['hijriDateFormat']);
$hijriMonth = GregorianHijri::hijriMonth($a,$m,$j,$GLOBALS['lang']);
array_push($monthsArray,$hijriMonth);
$sql = "SELECT * FROM tarshoh WHERE `datedurationm`";
$sql_result = mysql_query ($sql) or die ('request "Could not execute SQL query" '.$sql);
while ($row = mysql_fetch_assoc($sql_result)) {
$events[$row["event_date"]]["dawracat"] = $row["dawracat"];
$events[$row["event_date"]]["datedurationm"] = $row["datedurationm"];
}
$currntm = $events[$row["event_date"]]["datedurationm"];
$currnth = $events[$row["event_date"]]["datedurationh"];
if(!isset($_REQUEST['day'])){
if($j == $currntm){
$bg = "#79c04b";
}else{
$bg = "";
}
}else{
if($j == $newDay){
//$bg = "#cccccc";
}else{
//$bg = "";
}
}
///////////////////////
$gregorianId = 'gregorianDate'.$j;
$hijriId = 'hijriDate'.$j;
$function = "getDateInputs('".$gregorianId."','".$hijriId."')";
if (($j + $nb) % 7 == 1)
echo "<tr>";
echo "<td align=center style='font-size:10px;cursor:pointer' bgcolor='$bg' onclick=$function class='cel-calendar-border'>
<table border='0' class='font10px' width='30' cellspacing='0' cellpadding='0' >
<tr><td align='left'><span class='black'>$j</span></td></tr>
<tr><td align='right' class='red'>$day</td></tr></table>";
echo "<input type='hidden' name=$gregorianId id =$gregorianId value='$dateOutput'>";
echo "<input type='hidden' name=$hijriId id =$hijriId value='$hijriDate'>";
$j = $j+1;
echo "</td>";
}
} while ($valid);
$monthsArray = array_unique($monthsArray);
?>
</TABLE>
<div align="center" style="font-size:10px;font-family:'trebuchet MS';padding-top:2px;padding-bottom:2px;font-weight:bold" class="red">
<?php
$i=0;
foreach ($monthsArray as $key=> $value){
$i++;
echo $value;
if ($i < count($monthsArray)){
echo " / ";
}
}
echo " ".$year;
}
?>
</div>
and i get this tow date by this query :-
$sql = "SELECT * FROM tarshoh WHERE `datedurationm`";
$sql_result = mysql_query ($sql) or die ('request "Could not execute SQL query" '.$sql);
while ($row = mysql_fetch_assoc($sql_result)) {
$events[$row["event_date"]]["datestartm"] = $row["datestartm"];
$events[$row["event_date"]]["dateendm"] = $row["dateendm"];
}
And the calender here :-
echo "<tr>";
echo "<td align=center style='font-size:10px;cursor:pointer' bgcolor='$bg' onclick=$function class='cel-calendar-border'>
<table border='0' class='font10px' width='30' cellspacing='0' cellpadding='0' >
<tr><td align='left'><span class='black'>$j</span></td></tr>
<tr><td align='right' class='red'>$day</td></tr></table>";
echo "<input type='hidden' name=$gregorianId id =$gregorianId value='$dateOutput'>";
echo "<input type='hidden' name=$hijriId id =$hijriId value='$hijriDate'>";
$j = $j+1;
echo "</td>";

Why does time() malfunction after midnight in my MySQL query?

I have two tables that my Query affects. The tables are called flightSched & Alteration. In both tables the arrivalTime column is of type TIME.
The query runs just fine until the $CurrentTimePlus4Hours variable elapses midnight. When this happens, the query doesn't yield any records, although the table has data ranging from all times of the day and night. Find below my code.
$currentDay = date('l');
$CurrentTimeMinus30min = date('H:i:s', strtotime('-30 minutes'));
$CurrentTimePlus4Hours = date('H:i:s', strtotime('+240 minutes'));
$query2 = "SELECT * FROM flightSched WHERE don = '$currentDay'
AND depOrArriv='Arrival'
AND arrivalTime BETWEEN '$CurrentTimeMinus30min' AND '$CurrentTimePlus4Hours'
ORDER BY arrivalTime ASC ;";
$query2 .= "SELECT * FROM Alteration WHERE don = '$currentDay'
AND depOrArriv='Arrival'
AND arrivalTime BETWEEN '$CurrentTimeMinus30min' AND '$CurrentTimePlus4Hours'
ORDER BY arrivalTime ASC ;";
/* execute multi query */
if ($mysqli->multi_query($query2)) {
do
{
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_array()) {
echo "<tr " . $variable . "><td>";
echo '<img src="php/displayImage.php?id=' . $row['id'] . ' "align="middle" width="110" height="35" >' . " "
. $row['flightNo'] ;
$flightNo = $row['flightNo'];
echo "</td><td>";
echo $row['airline'];
echo "</td><td>";
echo $row['origin'];
echo "</td><td>";
echo $row['arrivalTime'];
echo "</td><td>";
echo $row['status'];
echo "</td></tr>";
if ($variable == 'id=basicBoard')
{
$variable = 'class=alt';
//echo $variable;
}
elseif ($variable == 'class=alt')
{
$variable = 'id=basicBoard';
//echo $variable;
}
}
$result->free();
}
/* print divider */
if ($mysqli->more_results()) {
// printf("-----------------</br>");
}
}
while (#$mysqli->next_result());
echo "</table> <br/> <br/>";
}
I have tried to figure out why this happens but failed to fix the issue. Can someone kindly point out where I am going wrong in the code?
I think you just need to compensate for the time lapse by offsetting what the "current" day is:
$midnight = strtotime('today');
$now = time();
$tomorrow = $midnight + 86400;
$diff = $tomorrow - $now;
$offset = $now;
// Number of seconds in 240 minutes = 14400
if ($diff <= 14400) {
$offset += $diff;
}
$currentDay = date('l', $offset);
$CurrentTimeMinus30min = date('H:i:s', strtotime('-30 minutes'));
$CurrentTimePlus4Hours = date('H:i:s', strtotime('+240 minutes'));

multiple checkboxes with php in table

I'm trying to build a simple attendance script which has the members in the users table. I have a script which builds the table and shows me today's date along with the rest of the month.
I also have a script which prints out the individual users, along side these users I want to have a checkbox in every column as far as the dates stretch out to.
I have a foreach statement for printing the users however if I put the <td><input type="checkbox"/></td> into this foreach statement this is only filling in the first column of dates.
If I put it in the for statement which outputs my <th> dates then it appends the checkbox in the <th> which is not what I want.
I'm not the best programmer so I'm not sure of the method that I should be using to achieve this, what I've done is simple so far if you look below you will be able to see how I've achieved this:
To reitrate the problem is that I am unable to append a checkbox per date value from the code below which prints dates from today's date to whatever it is set to.
Any ideas or input gladly welcomed.
public function viewall() {
$sth = $this->db->prepare("SELECT * FROM users");
$sth->execute();
/* Fetch all of the values of the first column */
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
$startDate = new DateTime();
$endDate = new DateTime('2013-09-31');
$days = array();
echo "<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>";
for ($c = $startDate; $c <= $endDate; $c->modify('+1 day')) {
echo "<th>".$c->format('d')."</th>"; }
echo "</tr>";
foreach($result as $row) {
$firstname = $row['firstname'];
$lastname = $row['lastname'];
echo "<tr>";
echo "<td>$firstname</td>";
echo "<td>$lastname</td>";
}
echo "<td><input type='checkbox'/></td></tr>";
echo "</table>";}
PICTURE 1 SHOWS THE PROBLEM
PICTURE 2 SHOWS HOW IT SHOULD LOOK
Here is the solution based on screen shots.
<?php
public function viewall() {
$sth = $this->db->prepare("SELECT * FROM users");
$sth->execute();
/* Fetch all of the values of the first column */
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
$startDate = new DateTime();
$endDate = new DateTime('2013-09-31');
echo "<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>";
for ($c = clone $startDate; $c <= $endDate; $c->modify('+1 day')) {
echo "<th>".$c->format('d')."</th>";
}
echo "</tr>";
foreach($result as $row) {
echo "<tr>";
echo "<td>" . $row['firstname'] . "</td>";
echo "<td>" . $row['lastname'] . "</td>";
for($c = clone $startDate; $c <= $endDate; $c->modify('+1 day')) {
echo "<td><input type='checkbox'/></td>";
}
echo "</tr>";
}
echo "</table>";
}
?>
EDIT: added clone to copy the object correctly
I am not very clear about your problem, but I think the following codes may help:
public function viewall()
{
$sth = $this->db->prepare("SELECT * FROM users");
$sth->execute();
/* Fetch all of the values of the first column */
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
$startDate = new DateTime();
$endDate = new DateTime('2013-09-31');
$days = array();
echo "<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>";
for ($c = $startDate; $c <= $endDate; $c->modify('+1 day'))
{
echo "<th>" . $c->format('d') . "</th>";
}
echo "</tr>";
foreach ($result as $row)
{
$firstname = $row['firstname'];
$lastname = $row['lastname'];
echo "<tr>";
echo "<td>$firstname</td>";
echo "<td>$lastname</td>";
$startDate = new DateTime();
$endDate = new DateTime('2013-09-31');
for ($c = $startDate; $c <= $endDate; $c->modify('+1 day'))
{
echo "<td><input type='checkbox'/></td>";
}
echo "</tr>";
}
echo "</table>";
}
I can not access db, so I cann't test it, what I want to say is that, tr or th stand for a table line, td is children, every line's children's count should be same.

How can I categorise MySQLi result set?

How can I change the code below so that I am only echoing each unique '$course' only once?
eg. currently my results look like =
ipswich-11:00-running
ipswich-12:00-flamingo rider
ipswich-14:00-lightning
norwich-13:10-ed is back
norwich-14:05-redrum
norwich-17:05-pickle
but I would like them to look like =
Ipswich
11:00-running
12:00-flamingo rider
14:00-lightning
norwich
13:10-ed is back
14:05-redrum
17:05-pickle
I thought about doing a mysqli query in a for each loop, but surely there is a better way?
My code =
<?php //connection block
if ($mysqli->connect_error) {die('Connect Error: ' . $mysqli->connect_error);}
$today = date("Ymd");
$query = "SELECT horse, course, time, date FROM dailytips WHERE date = $today ORDER BY course, time";
$result = $mysqli->query($query);
$today_uk = " " . date("d/m/y");
while($row = $result->fetch_array())
{ $rows[] = $row; }
echo "<h2>tips for" .$today_uk. "</h2>";
foreach($rows as $row)
{
$date = $row['date'];
$date = date("d/m/y", strtotime($date));
$horse = $row['horse'];
$time = $row['time'];
$course = $row['course'];
echo
'<div style= "width:600px; font-family:verdana;">
<div style="float:left; width:400px; margin-bottom:10px; margin-top10px;">
'.$row['course']. "-" .$row['time'] . "-" . $row['horse'] .'
</div>' ;
}
$result->close();
$mysqli->close();
?>
I guess you could nest a foreeach statement inside another.
so...
$query = "SELECT course, FROM dailytips WHERE date = $today ORDER BY course, time";
while($row = $result->fetch_array())
{ $rows[] = $row; }
echo "<h2>tips for" .$today_uk. "</h2>";
foreach($rows as $row) {
$query = "SELECT horse, time, date FROM dailytips WHERE course = $row['course'];
while($row = $result->fetch_array())
{ $rowDetail[] = $rowDetails; }
foreach($rows as $row) {
$date = $row['date'];
$date = date("d/m/y", strtotime($date));
$horse = $row['horse'];
$time = $row['time'];
$course = $row['course'];
echo
'<div style= "width:600px; font-family:verdana;">
<div style="float:left; width:400px; margin-bottom:10px; margin-top10px;">
'.$row['course']. "-" .$row['time'] . "-" . $row['horse'] .'
</div>' ;
}
}
I would consider putting your results in a table opposed to DIVs as this would seem to fit what you are trying to do much better. Set the table up before the loop and close once the loop has been exited.

Categories