Trying to find total vacancy days in investment properties...
I'm getting info from mysql putting it into a looped array to find the difference between dates in different rows.
I am able to return the difference between each "move out" and "move in" dates, but am unable to get a running total.
The code below returns this...
Difference between 2014-01-25 and 2014-01-27 on Property# 7 = 2
Difference between 2014-11-03 and 2014-11-23 on Property# 7 = 20
mysql_select_db($database_rent, $rent);
$query_RS_Vac = "SELECT Properties.PropId, Tenants.TenantId, Tenants.PropertyID, Tenants.TenantAdress, Tenants.MoveIn, Tenants.MoveOut, Properties.P_GpNo FROM Properties, Tenants WHERE Tenants.PropertyID=Properties.PropId AND Tenants.TenantAdress = "7"
ORDER BY Tenants.TenantId ";
$result = mysql_query($query_RS_Vac) or die ("no query");
$result_array = array();
while ($row = mysql_fetch_array($result)) {
$values = array($row['MoveIn'],$row['MoveOut'], $row['TenantAdress']);
array_push($result_array,$values);
}
$it = 0;
$PropId=$values[2];
while($it<count($result_array)){
// if neither begin and end are NULL
if($result_array[$it][1]!= null & $result_array[$it+1][0]!=null){
$datetime1 = new DateTime($result_array[$it][1]);
$datetime2 = new DateTime($result_array[$it+1][0]);
$diff = $datetime1->diff($datetime2);
$days2= $diff->format("%a");
echo "Difference between ".$datetime1->format("Y-m-d")." and ".$datetime2->format("Y- m-d")." on Property# " . $PropId . " = " . $days2 . "<br/>";
}
$it++;
}
2 ways
$total_days[]=$days2;
array_sum($total_days);
or
$total_days+=$days2;
Related
I have a small PHP page which takes data from MySQL and displays it via PHP in a monthly calendar. I'm having trouble arranging the data properly within an array to get the desired output.
First, I will describe what I would like to happen:
students come to classes on regular days of the week
they can also make or cancel reservations
the calendar also displays days when the school is not open
In order to display this data on the calendar, I use MySQL to output data from a variety of sources, and then input that into an array with PHP, which I sort by date and output.
My issue is, I would like to be able to handle more than one row of data per day, but because I am using the date as the key, I am limited on only displaying one result per day. If I use a loop to append the date with a counter in the key, I get overlapping results in situations where someone made a reservation and then cancelled that reservation on the same day.
As for my code...
First, I check to see if the student is registered in a weekly class, then input that class into the array.
$sql = "SELECT StudentDB.studentid, ClassDB.classID, ClassDB.class_level, ClassDB.class_title, ClassDB.time, ClassDB.teacher, StudentDB.first_name, StudentDB.last_name, StudentDB.payment_amount, ClassDB.day
FROM ClassDB
INNER JOIN RegDB ON ClassDB.classID = RegDB.classid
INNER JOIN StudentDB ON StudentDB.studentID = RegDB.studentid
WHERE StudentDB.studentid = '$studentid'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) { // DISPLAY REGULAR CLASS DATA
$dayofclass = $row['day'];
$class_level = $row['class_level'];
$class_title = $row["class_title"];
$day = $row["day"];
$class_time = $row["class_time"];
$time = $row["time"];
// check which dates match the days of the week and store in an array
for ($i=1;$i<=$n;$i++){
if ($i<10) {
$i = "0" . $i;
}
$day=date("l",strtotime($yearmonth.$i)); //find weekdays
if($day==$dayofclass){
$time = date("H:i",strtotime($row['time']));
$dates[]=$yearmonth.$i;
$datesdata[$yearmonth.$i] = "0";
$timedata[$yearmonth.$i] = $time;
$classiddate[$yearmonth.$i] = $row['classID'];
}
}
}
echo "</table>";
$conn->close();
}
After that, I check for specific reservations (cancelations, irregular reservations, waitlists) and input them into the array:
$lowerlimit = $yearmonth . "01";
$upperlimit = $yearmonth . "31";
$sql = "SELECT AttendanceDB.*, ClassDB.*
FROM StudentDB
INNER JOIN AttendanceDB ON StudentDB.studentid = AttendanceDB.studentid
INNER JOIN ClassDB ON AttendanceDB.classid = ClassDB.classID
WHERE StudentDB.studentid = '$studentid'
AND AttendanceDB.class_time >= '$lowerlimit'
AND AttendanceDB.class_time <= '$upperlimit'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$loopcount = 0;
// store furikae data in the array
while($row = $result->fetch_assoc()) {
$phpdate = strtotime( $row["class_time"] );
$time = date("H:i",strtotime($row['time']));
$mysqldate = date( 'Y-m-d', $phpdate );
$loopcount++;
$mysqldate = $mysqldate . "+" . $loopcount;
// $loopcount++;
// $mysqldate = $mysqldate . "+" . $loopcount;
$previousdate = $mysqldate;
$previousfurikae = $row['furikae'];
if ($row["furikae"] == 3){
$dates[]=$mysqldate;
$datesdata[$mysqldate] = "1";
$timedata[$mysqldate] = $time;
$classiddate[$mysqldate] = $row['classID'];
} elseif ($row["furikae"] == 8 OR $row["furikae"] == 7) {
$dates[]=$mysqldate;
$datesdata[$mysqldate] = "3";
$timedata[$mysqldate] = $time;
} elseif ($row["furikae"] == 2) {
$dates[]=$mysqldate;
$datesdata[$mysqldate] = "2";
$timedata[$mysqldate] = $time;
}
}
}
$conn->close();
Then finally I check the school calendar and input the days off into the array:
$sql = "SELECT *
FROM SchoolScheduleDB
WHERE date >= '$lowerlimit'
AND date <= '$upperlimit'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// store furikae data in the array
while($row = $result->fetch_assoc()) {
$phpdate = strtotime( $row["date"] );
// $time = date("H:i",strtotime($row['time']));
// $mysqldate = date( 'Y-m-d', $phpdate ) . " " . $time;
$mysqldate = date( 'Y-m-d', $phpdate );
$dates[]=$mysqldate;
$datesdata[$mysqldate] = "666";
}
}
$conn->close();
The way I intended it to work was that:
First the regular classes would be input
Then any reservations would overwrite the original plans
And finally the school calendar would overwrite everything
Currently, this functions as it should, but it is limited to displaying 1 result per day, but I would like to be able to display more than 1 result per day for students who come to multiple classes.
Thank you for your help. If I made any mistakes in my question or my question is unclear I will do my best to revise it.
You can make a Sub-Array for each date by using edged brackets:
$data[20180528][] = 'aa';
$data[20180528][] = 'bb';
$data[20180529][] = 'cc';
$data[20180529][] = 'dd';
$data[20180529][] = 'ee';
will give you an Array like this:
20180528 => aa
=> bb
20180529 => cc
=> dd
=> ee
<?php
require 'dbfunction.php';
$con = getDbConnect();
if (!mysqli_connect_errno($con)) {
$queryStr = "SELECT * " .
"FROM crewlist WHERE crew_name = 'Peter'";
}
$result = mysqli_query($con, $queryStr);
while ($row = mysqli_fetch_array($result)) {
$a = new DateTime($row["start_hour"]);
$b = new DateTime($row["end_hour"]);
$shift1 = $a->diff($b);
$c = new DateTime($row["start_hour2"]);
$d = new DateTime($row["end_hour2"]);
$shift2 = $c->diff($d);
if ($shift1 > 60*60*14) {
echo 'no';
}
?>
I am trying to deduce the difference between my shift timings, with the condition of (for e.g. shift 1 not exceeding 14 hours). Thanks in advance. The fields of my form is using time as the type.
Convert your start date and end date into timestamp and then take difference of both.
$diff = abs($start-$end)
if($diff > 60 * 60 *14 ){
// Your desired statement
}
if that difference exceeds to 60*60*14 then it will exceed to 14 hour.
Mysql database timestamp query using php
I inserted into database a timestamp value set to 3 hours a head as follows
//For 3 hours ahead of time
$reciever_time = date("Y-m-d H:i:s", strtotime('+3 hours'));
now once its upto 3 hours, i need to echo "3 hours is due" but the code below keeps echoing "its not yet 3 hours" even though
3 hours is due. any help
<?php
$link = mysqli_connect("localhost", "sectona", "secBBN", "sectonadb");
$q = "SELECT id,reciever_time FROM indextime WHERE id='10'";
$qu = mysqli_query($link, $q);
while($row=mysqli_fetch_array($qu, MYSQL_ASSOC)){
$id = $row['id'];
$timest = $row['reciever_time'];
}
//60secx10min is 600milisec
//60secx30min is 1800
// 30 min = 1800
// 1 hour = 1800 x2
//12 hour = 3600 x12
//1 day = 3600 x24
$time = strtotime($timest);
$curtime = time();
// execute data that is due in 3 hours
if(($curtime-$time) >= 10800) {
print "3 hours is due then update";
}
else{
print "its not yet 3 hours";
}
?>
Try this:
if(($time - $curtime) >= -10800) {
print "3 hours is due then update";
} else {
print "its not yet 3 hours";
}
Only convert the 10800 to negative.
You can try:
$link = mysqli_connect("host","user","password","DBname");
$q = "SELECT id,reciever_time FROM indextime WHERE id='10' LIMIT 1";
$qu = $link->query($q);
$row = mysqli_fetch_object($qu);
$id = $row->id;
$timest = $row->reciever_time;
$time = strtotime($timest);
$curtime = time();
$message = ($curtime - $time) >= 10800 ? "3 hours is due then update" : "its not yet 3 hours";
print $message;
in PHP you want to use the the date_diff function to get the difference in time
try:
if(date_diff($time,$curtime) >= 10800){
$sqlStr = "SELECT name, datescheduled
FROM table
WHERE datescheduled > NOW()
ORDER BY datescheduled DESC";
I would like to echo a table with the results above. I would like a row for each day for the next 90 days regardless of whether or not the MySQL table has an entry for that day. How can I do this?
Add:
$query1 = mysql_query($sqlStr);
echo "<table><tr>";
echo "<th>Name</th><th>Date Scheduled</th>";
while ($rows = mysql_fetch_assoc($query1)) {
echo "<td>" .$rows['name']. "</td>";
echo "<td>" .$rows['datescheduled']. "</td>";
}
echo "</tr><table>";
//select rows for next 90 days and read them into $rows
//use datescheduled as the key
//assumes there will only be 1 row per date and datescheduled is in Y-m-d format
$sqlStr = "SELECT name, datescheduled
FROM table
WHERE datescheduled > NOW()
AND datescheduled < date_add(now(),INTERVAL 90 DAY)
ORDER BY datescheduled DESC";
$rs = mysql_query($sqlStr);
$rows = array();
while($r = mysql_fetch_assoc($rs)) {
$rows[$r['datescheduled']] = $r;
}
//add missing dates to $rows with name = false
$begin = new DateTime();
$end = new DateTime();
$end->modify('+90 day');
$interval = new DateInterval('P1D');
$period = new DatePeriod($begin, $interval, $end);
//iterate through the next 90 days
foreach ($period as $dt) {
$date_key = $dt->format( "Y-m-d" );
if(!isset($rows[$date_key])) {
//table doesn't contain a row for this date, so add it
$rows[$date_key] = array('datescheduled' => $date_key, 'name' => false);
}
}
//do something with $rows
So you can use this basic setup. I assume based on your wording that there would only be one entry per row, but it would be easy to adjust accordingly.
//Get the current date
$date = date('Y-m-d');
//Set the table header
$str = '<table><thead><tr><th>Name</th><th>Date</th></tr></thead><tbody>';
//START THE WHILE LOOP GETTING THE FETCH ASSOC
//Go through for 90 days
for ( $i = 0; $i < 90; $i++ ) {
$str .= '<tr>';
if ( $row['date'] == date('Y-m-d', strtotime('-'.$i.' day', $date)) {
$str .= '<td>'.$row['name'].'</td><td>'.$row['date'].'</td>';
} else {
$str .= '<td></td><td></td>';
}
$str .= '</tr>';
}
//END WHILE LOOP NOT INCLUDED
$str .= '</table>';
echo $str;
I am searching up a database to find the past 7 days worth of data, accumulated.
It works perfectly, but I currently have seven editions of the same code - so I want to loop it somehow, however if I do that, how do I loop it correctly and name the variables. Aside from naming the variables (day_X_) I think I should be able to loop it 7 times fairly easily...
// Get the current day
$graph_day_1_date_lower = date('Y-m-d') . " 00:00";
$graph_day_1_date_upper = date('Y-m-d') . " 23:59";
$graph_day_1_name = date('D') . " (Today)";
/* Successes */
$graph_day_1 = mysqli_query($con,
"SELECT COUNT(`id`) AS num FROM `hidden`
WHERE submittedtime >= '$graph_day_1_date_lower'
AND submittedtime < '$graph_day_1_date_upper'
AND u_s_code='C001'")
or die(mysqli_error($con));
$graph_day_1_row = mysqli_fetch_assoc($graph_day_1);
$graph_day_1_count = $graph_day_1_row['num'];
$graph_total_count = $graph_day_1_count;
/* Errors */
$graph_e_day_1 = mysqli_query($con,
"SELECT COUNT(`id`) AS num FROM `hidden`
WHERE submittedtime >= '$graph_day_1_date_lower'
AND submittedtime < '$graph_day_1_date_upper'
AND u_s_code='E001'")
or die(mysqli_error($con));
$graph_e_day_1_row = mysqli_fetch_assoc($graph_e_day_1);
$graph_e_day_1_count = $graph_e_day_1_row['num'];
$graph_e_total_count = $graph_e_day_1_count;
I will then print the two total counts for each day
Here's what you would want to do:
$today = time(); // or use your upper / lower bounds
$daysToShow = 7;
$dayData = array();
for($i = 0; $i < $daysToShow; $i++){
$dateToCheck = $today + ($i * 24 * 60 * 60); // add a day each time $i goes up
$dataArray = mysql_fetch_assoc($yourDataHere); // replace with your mysqli query using $dateToCheck
$dayData[] = $dataArray; // add to array
}
foreach($dayData as $day){
echo $day['name']; // print out your info here
}