I am building a script to display some 24 hour charts. I am attempting to make 12 charts. One 24 hour (last hour) chart for each five minute data set i have collected. I am running accross an issue where my mysql command will not update the $hour_position. I've read many while loop inside while loop questions and have tried to construct a foreach alternative, and also tried to reset the query array, but none of this has worked. Any comments or links to another thread that can solve this problem would be appreciated.
Thanks in advance.
$hour_position = 00;
$htime = -1;
$date = date('Y-m-d H:i:s');
$date = strtotime($date);
$date = strtotime($htime." day", $date);
$date = date('Y-m-d H:i:s',$date);
while($hour_position < 60){
$price_history_qry = mysqli_query($con,"SELECT * FROM `dbTable` WHERE `server_time` > '$date' AND EXTRACT(MINUTE FROM `server_time`) like $hour_position ORDER BY `server_time` ASC");
while($result = mysqli_fetch_array($price_history_qry)){
//Create a couple of arrays to build a chart.
}
//Build chart here
echo $chart;
$hour_position = $hour_position +05;
}
Try putting $hour_position in quote like
' $hour_position '
or you can use
". $hour_position ."
Your query has a small mistake. The variable inside single quotes will not be evaluated as variable. Check this. you need to change the select query like below.
$price_history_qry = mysqli_query($con,"SELECT * FROM `dbTable` WHERE `server_time` > '".$date."' AND EXTRACT(MINUTE FROM `server_time`) like ".$hour_position." ORDER BY `server_time` ASC");
And i haven't find any update query in your code. As you said you are using the update query inside while loop. So first check whether the variable has the value and then check whether it entering to while loop like below.
$result = mysqli_fetch_array($price_history_qry)
var_dump($result);
while($result){
//Create a couple of arrays to build a chart.
var_dump("entered");
}
Try to use var_dump() function to debug.
Hope it helps you.
Related
I asked a question yesterday in adding together datetime intervals and was pointed to this thread - How we can add two date intervals in PHP
This is great and makes sense. However, when I try to do what the submitted answer says in a foreach loop, I'm ending up with an incorrect result.
This is a function I have made that gets all the clock in times and out times of staff, they are stored in the db and are created using PHP's date(H:i:s).
My function gets all the in and out times of any given employee, and my reporting feature I'm working on needs to display the total amount of hours they have worked.
I tried to achieve this by converting the times to datetime objects and using ->diff to get the intervals and thus calculating that days hours, I am then trying use a foreach loop to add the intervals together thus giving me a sum total of the hours worked in any given date range.
The whole function together is this:
function getTotalHours($staff_id,$from_date,$to_date){
$sql = "SELECT * FROM oc_staff_times WHERE date BETWEEN '$from_date' AND '$to_date' AND staff_id = '$staff_id'";
$result = $this->conn->query($sql);
if ($result->num_rows > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
$base_time = new DateTime('00:00');
$total = new DateTime('00:00');
foreach ($data as $time) {
$in = new DateTime($time['clock_in_time']);
$out = new DateTime($time['clock_out_time']);
$interval = $in->diff($out);
$base_time->add($interval);
}
return $total->diff($base_time)->format("%H:%I");
}
}
I was hoping to get a monthly total, however it seems I'm only getting one days total as my final result. Here is a screen shot of the UI (the total hours are crudely circled) this also shows the time stamps my function should be adding together.
You can do this in a single query instead. Use TIMEDIFF() to get the difference for each row, then convert those to seconds by using TIME_TO_SEC(), SUM() those up and put it back into time-format with SEC_TO_TIME() - all in MySQL!
SELECT SEC_TO_TIME(SUM(TIME_TO_SEC(TIMEDIFF(`clock_out_time`, `clock_in_time`))))
FROM `oc_staff_times`
WHERE `staff_id` = ?
AND `date` BETWEEN ? AND ?
Making your function with a prepared statement..
function getTotalHours($staff_id, $from_date, $to_date){
$sql = "SELECT SEC_TO_TIME(SUM(TIME_TO_SEC(TIMEDIFF(`clock_out_time`, `clock_in_time`))))
FROM `oc_staff_times`
WHERE `staff_id` = ?
AND `date` BETWEEN ? AND ?";
$stmt = $this->conn->prepare($sql);
$stmt->bind_param("sss", $staff_id, $from_date, $to_date);
$stmt->execute();
$stmt->bind_result($totalTime);
$stmt->fetch();
$stmt->close();
return $totalTime;
}
SQL fiddle showing the query in action http://sqlfiddle.com/#!9/525b83/7
The answer from Qirel offers a nice way to do this in SQL, however if you want to understand why your code didn't work:
$base_time = new DateTime('00:00'); does not create an interval, it's a date. It means that if you add 24 hours to it and ask only the time part, it will show '00:00' because you end up the day after.
One solution would have been to declare $base_time as an interval, for example like this:
$base_time = new DateInterval('PT0S');
And at the end output directly like this:
$base_time->format("%H:%I");
So I am working on a simple website and I ran into a problem. I have a subscription based website and I have a date expired for when their subscription ends. This all works well, but when I tried to display the expiration date I ran into problems. The first 3 lines are what i have been trying. It seems as if the timestamp isnt correctly being transferred from the database because when I did my test at the button, this displayed the correct date. The top 3 lines always give me this: 1970/01/01
// Get Expiration Date
// Always gives me 1970/01/01
$datexpire = "SELECT date-expire FROM users WHERE username='{$_SESSION['username']}'";
$timestamp = mysqli_query($link, $datexpire);
$date = date("Y/m/d",$timestamp);
//This works
$timestamp2 = 1537847863;
$date2 = date("Y/m/d",$timestamp2);
If anyone could help that would be much appreciated
i think your code should be something like
$datexpire = "SELECT date-expire FROM users WHERE username='{$_SESSION['username']}'";
$result = mysqli_query($link, $datexpire);
$row=mysqli_fetch_assoc($result));
$timestamp = $row['date_expire'];
$date = date("Y/m/d", $timestamp);
echo $date;
please check for column name.. if it is date-expire or date_expire ??? (dash or underscore ??)
mysqli_query returns a mysqli_result object or a boolean value.
You want to fetch a row from your given object, like so:
$datexpire = "SELECT `date-expire` FROM users WHERE username='{$_SESSION['username']}'";
$result = mysqli_query($link, $datexpire);
$row = mysqli_fetch_assoc($result);
$date = date("Y/m/d", $row["date-expire"]);
I've been trying many different ways to pass the dates into the query as a variable, and nothing I've tried has worked. When I put the exact dates in there like below, the query works fine.
$ly = mysqli_query($link,'SELECT SUM(rtype_price) FROM client WHERE date BETWEEN "2017-01-01" AND "2017-12-31"');
while($row1 = mysqli_fetch_array($ly))
{
$ly_cash = $row1['SUM(rtype_price)'];
}
For example, I've been trying something like this:
$ly_start = date('Y-m-d', strtotime('first day of previous year'));
$ly_end = date('Y-m-d', strtotime('last day of previous year'));
then passing $ly_start and $ly_end into the query like this:
$ly = mysqli_query($link,'SELECT SUM(rtype_price) FROM client WHERE date BETWEEN "$ly_start" AND "$ly_end"');
Inverting the quotes did the trick. This works:
$ly = mysqli_query($link,"SELECT SUM(rtype_price) FROM client WHERE paid = 1 AND date BETWEEN '$ly_start' AND '$ly_end'");
while($row1 = mysqli_fetch_array($ly))
{
$ly_cash = $row1['SUM(rtype_price)'];
}
Thank you ild_flue
My question is similar to [this][1] but the solution provided there doesn't work for me.
I have a DB and I have one column called birth that contains a date in the format year-day-month 00:00:00. Now I want to extract from the DB all the records which birth is between two dates.
The birth value has been inserted in the DB with this code
$date = $day . "-" . $month. "-" . $year;
$a = strptime($date, '%d-%m-%Y');
$DB_date = date('Y-m-d H:i:s',mktime(0, 0, 0, $a['tm_mon']+1, $a['tm_mday'], $a['tm_year']+1900));
To extract the dates I am using this code:
$stmt = $conn->prepare('SELECT * FROM database WHERE `birth` BETWEEN ? AND ?');
$start_date = '1990-01-01';
$stop_date = '1995-01-01';
$stmt->bind_param('ss',$start_date,$stop_date);
$stmt->execute();
$result = $stmt->get_result();
but it doesn't find anything so $result->num_rows is equal to 0 and it doesn't give any errors so the problem must be in the comparison of the dates.
Birth column format is y-d-m hour min sec. But in your where clause you are ignoring hour minute second factor.
Replace:
$start_date = '1990-01-01';
$stop_date = '1995-01-01';
With this:
$start_date = '1990-01-01 00:00:00';
$stop_date = '1995-01-01 00:00:00';
Kindly try it and let me know if it works
I found the solution
The code in my question works if the data type of the column in the DB is datetime and you also need to make sure that $start_date is older than $stop_date. I still wonder though why it didn't work with the date data type.
I had the same issue. I found another thread with the same problem (not sure how to duplicate this thread) here
However just to sum up,
They managed to get the desired results by bracketing the question marks for the params.
$stmt = $conn->prepare('SELECT * FROM database WHERE `birth` BETWEEN (?) AND (?)');
$start_date = '1990-01-01';
$stop_date = '1995-01-01';
$stmt->bind_param('ss',$start_date,$stop_date);
$stmt->execute();
$result = $stmt->get_result();
Hope this helps.
I am unable to assign only date to a php variable from datetime field of a MySQL table. I am using PHP 4, I know how to do it in PHP 5.
Can someone help as to what is missing from the below php code.
$dc = mysql_query("SELECT * FROM INVHDR WHERE Invdate BETWEEN '2011-04-01' AND '2012-03-31'");
while ($dc2 = mysql_fetch_assoc($dc)) {
$invno = $dc2['Invno']; // Here Invno is a datetime field type
$invdat3 = $dc2['Invdate'];
$date_array = explode("-", $invdat3);
$invdat = sprintf('%02d/%02d/%4d', $date_array[2], $date_array[1], $date_array[0]);
}
If you just want to display the date portion, you could use the DateTime class:
echo DateTime::createFromFormat("Y-m-d H:i:s", "2012-12-24 12:13:14")->format("d/m/Y");
// 24/12/2012
//Edited for double echo typo.
There is a link I find extremely useful when it comes to date manipulations:
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
one can easily find the solution there:
SELECT *, DATE(Invdate) as Inv_date ...
Do it directly in MySQL:
select DATE_FORMAT('2012-12-24 12:13:14', '%Y/%m/%d')
So your query will look like this:
SELECT DATE_FORMAT(Invdate, '%Y/%m/%d') FROM INVHDR WHERE Invdate BETWEEN '$startdat' AND '$enddat'