PHP using TIME from database to calculate hours - php

<?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.

Related

round down to nearest 5 mintues php mysqli

I"m trying to get this time code to round down to the nearest time
example if the time listed is 10:28, then i want it to show 10:25
What I have is (the time modify is required)
<?php
include('../../database/2ndconnection.php');
$sql="SELECT * FROM raid ORDER BY TimeRecord DESC LIMIT 1";
$result=mysqli_query($dbcon,$sql);
while($rows=mysqli_fetch_array($result)){
$dateStr = $rows['TimeRecord'];
$pst = new \DateTime($dateStr);
$pst->modify("-3 hours");
$est = new \DateTime($dateStr);
} ?>
PST: <?php echo $pst->format('H:i'); ?>
<br>EST: <?php echo $est->format('H:i'); ?>
thanks in advance for your help
Insert this:
<?php
$currentMinutes = $time->format('i');
$minutesToSubtract = $currentMinutes % 5;
$time = $time->sub(new DateInterval('M' . $minutesToSubtract));
?>
$currentMinutes will hold the current number of minutes, using %, you can compute the minutes that need to be subtracted, and afterwards you subtract them through the sub function
It could be integrated into your code as following:
<?php
include('../../database/2ndconnection.php');
$sql="SELECT * FROM raid ORDER BY TimeRecord DESC LIMIT 1";
$result=mysqli_query($dbcon,$sql);
while($rows=mysqli_fetch_array($result)){
$dateStr = $rows['TimeRecord'];
$pst = new \DateTime($dateStr);
$pst->modify("-3 hours");
$est = new \DateTime($dateStr);
}
$currentMinutes = $pst->format('i');
$minutesToSubtract = $currentMinutes % 5;
$pst = $pst->sub(new DateInterval('M' . $minutesToSubtract));
?>
PST: <?php echo $pst->format('H:i'); ?>
<br>EST: <?php echo $est->format('H:i'); ?>

How can I generate a random number every x amount of months?

Starting with the number 9 and using php, I would like to be able to count up from there, and echo out the next number in increments of 1.
So, number 9, then after 1 month the number would change to 10, then another month 11, then 12 etc., with no maximum number/stop point.
How can I accomplish this? So far I have the below code.
$number = 9;
$output = $number + 1;
echo $output;
Is there a way to set this to increase once a month?
You can do this with the PHP date()-function. This is one example of doing it if you are not dependent on the day of the month, but adding day functionality is possible and should be quit easy.
$startNumber = 9;
$startYear = 2015;
$startMonth = 9;
$currentYear = intval( date( "Y" ) );
$currentMonth = intval( date( "n" ) );
$monthsToAdd = ( ( $currentYear - $startYear ) * 12 )
+ ( $currentMonth - $startMonth );
echo $startNumber + $monthsToAdd;
From your question, I'd say:
$number = 9;
$output = date('n') + $number;
echo $output;
But that depends on what you are trying to accomplish. You can also wrap the number around the date() with a modulo.
However this is nothing random. If you want to create a random number every month like your topic suggests, use the month as the random seed.
srand(date('n'));
$number = rand();
a very inefficient way would be
<?php
function increm($duration){
while ($i<$duration) {
$i++;
}
return true;
}
$number = 9;
$start = time();
$i = 0;
while (1){
increm(3600*24*30);
$i++;
// Do your code
}
?>
this script would have to be run continuously for months.
A better way would be
<?php
$number = 9;
if(!file_exists('date.txt')){
$date=date('n');
file_put_contents( (string)time());
$date = 0;
}
else{
$date= file_get_contents('date.txt');
$date= date()-(int)$date;
$date= floor($date/(24*3600*30));
}
// do whatever you may
?>
But this script would increase it whenever called as the first open date would be stored. Will work forever (till UNIX can timestamp).
for this purpose you have to store the number in the database, compare with current unix timestamp and update it when the new month is reached.
2 database columns: count_month int(10) and next_month int(10) where next_month will contain the unix timestamp of the first day of the next month. you can run it with cronjobs or on production.
<?php
$now = strtotime("now");
$next_month = strtotime("first day of next month");
if ($query = $dbconnect->prepare("SELECT next_month FROM table1")) {
$query->execute();
$query->bind_result($compare_time);
$query->store_result();
$row_count = $query->num_rows;
if ($row_count > 0) {
while ($query->fetch()) {
if ($compare_time < $now) { // you reached the 1th of the next month time to update
if ($query2 = $dbconnect->prepare("UPDATE table1 SET count_month=count_month +1, next_month=?")) {
$query2->bind_param('i', $next_month);
$query2->execute();
$query2->close();
}
}
}
}
$query->free_result();
$query->close();
}
?>

Mysql database timestamp query using php

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){

Get totals of an array in a loop

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;

How should I make this SQL Query more efficent

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
}

Categories