Get average time between several dates for one entry - php

I am not really sure how to explain this, but basically what I am trying to do is get the average time that it takes between a set of dates. This is what the database table looks like
id | offer_id | user | date | date_completed
----------------------------------------------------
1 | 123 | test | 1352265988 | 1352265995
2 | 123 | admin| 1352266004 | 1352266022
3 | 123 | kira | 1352264754 | 1352271946
I need to get the average time between the 2 timestamps and calculate them together so I can echo it out in my code. I am sure this would be done with a foreach statement, but I have no idea how to go about doing it. If there is anyone that can point me in the right direction that would be great!

Unless I'm missing something, you can just do it in a single query:
SELECT AVG(date_completed - date)
FROM myTable

Use the SQL-function AVG for each of the colums (date and date_completed). Than, you can just substract each average time and you will get your result you are searching for.

Related

Splitting the result in while loop

Here i use a query for getting last two collision occurring dates of a licence number as follows:
<?php
$licence=$_POST['licence'];
$sel=mysqli_query($con,"select cdate from tblcollision where licence_number='$licence'");
while($s=mysqli_fetch_row($sel))
{
echo $s[2];
}
?>
I wish to split the result in to separate fields. That means date1 in a text field and date2 in another text field. Actually i didn't get any idea. Please help me.
My db design is
+--------------------------------------------------+
| CID | ID | LICENCE_NUMBER | CDATE |
+--------------------------------------------------+
| 1 | 1 | 3/4858/2012 | 2018-02-06 |
| 2 | 1 | 3/4858/2012 | 2018-03-20 |
+--------------------------------------------------+
As stated by mickmackusa, if the query is filtered for a single licence number, there is no point to group result in the SQL statement and then explode the result in PHP. Just read the rows and make the calculation on the resulting dates.
However, in a more general way, if dealing with several licences, grouping can be done within the SQL statement. Despite the added cost of exploding the result, it will simplify the grouping process.
You need to use GROUP_CONCAT in your query:
SELECT licence_number, GROUP_CONCAT(cdate) AS Events_dates
FROM tblcollision
WHERE licence_number='$licence'
GROUP BY licence_number;
This will return:
3/4858/2012 | 2018-02-06, 2018-03-20

Join Row to Previous Closest Date Row

Database data:
id | account | date | random_data
1 | 1 | 01/01/2013 | qw
2 | 2 | 05/01/2013 | er
3 | 2 | 09/01/2013 | ty
4 | 1 | 05/01/2013 | ui
5 | 2 | 11/01/2013 | op
6 | 1 | 12/01/2013 | as
Hi, so let's say I want the records starting from 05/01/2013 - note that prev_date for the 1st row still shows an earlier date than 05/01 meaning that the whole table still needs to be searched.
Result data:
account | cur_date | random_data | prev_date | prev_rand_data
1 | 05/01/2013 | ui | 01/01/2013 | qw
1 | 12/01/2013 | as | 05/01/2013 | ui
2 | 05/01/2013 | er | null | null
2 | 09/01/2013 | ty | 05/01/2013 | er
2 | 11/01/2013 | op | 09/01/2013 | ty
So I'm not sure what is the best, most optimized query I could use for this. I'm not opposed to a php solution but not sure how much better that would be. Some ideas I've considered:
Some sort of join on the same table - not sure how though
Sub queries on the select -
select date as cur_date
, (select max(date)
from table
where date < cur_date
group by account)
as prev_date... - this seems like it could be incredibly intensive
Session variables - set a session variable on each row which will be the previous data for the next row e.g.
select date as cur_date
, #prev_date as prev_date
, #prev_date:=date...
Has anyone had any experience with a problem like this and was there a good solution? Are there any positives negatives with any of the ideas I have that could cause problems in the future?
I would use a combination of sql and application code. Since I am not a php programmer, I will only describe the logic to use for the application part.
First the query.
select account, date, random_data
from thetable
where date >= YourDateVariable
union
select account, date, random_data
from thetable join
(select account acc, max(date) maxdate
from thetable
where date <= YourDateVariable
group by account) x on account = acc and date = max(date)
where date <= YourDateVariable
order by account, date
For the application code, do this:
Set a variable called ThisAccount to 0.
Set a row counter variable to 0.
Create an empty 2D array
Start looping through your query results
Put the account value and random data into the first two columns
of the next available row of the array
Compare the account value to the value of the ThisAccount variable.
If they are the same, get the previous date and random data from
the previous row in the array.
Set the ThisAccount variable to the current account value.
Increment your row counter variable
End of loop.

MySQL sql query LIKE to get current opening hours

So, in my mysql database I am storing days and hours open in one field, called days, the data is stored in the following format:
[Monday:9:17[Tuesday:9:17[Wednesday:10:18[
As you may've guessed, it goes: [Day:From:Till and brackets are just seperatars for PHP to distinguish how many days are there.
I've been thinking all day what query would be but I could not figure out, so basically I need to get current date and time using PHP:
date(l); // Day in full text representation.
date(G); // current hour in 24 hour format.
So basically I need a query which in simple english would sound like:
SELECT all FROM businessdetails WHERE column date CONTAINS [current date] and :#:# numbers to be less than current hour and greater than current hour.
Help? My brain is melting by now.
So honestly the best thing to do is to normalize your database so you can do better queries. BUT I love to see if I can solve impossible situations so here is what you can do!
This will check all the business that are open on Tuesday at 11am
SELECT * FROM `businessdetails` WHERE `date` REGEXP 'Tuesday:(0|1|2|3|4|5|6|7|8|9|10|11):(11|12|13|14|15|16|17|18|19|20|21|22|23)[^0-9]'
(Funny thing I've found I can't seem to escape the [ in the column so I had to make sure the Regex doesn't have any extra digits at the end or it may erroneously match 2 and 20 or something.)
Here's how you can generate that REGEXP string via PHP:
<?php
$regexp = date('l') . ':(' . join('|', range(0, date('G'))) . '):(' . join('|', range(date('G'), 23)) . ')[^0-9]';
DISCLAIMER I don't actually recommend doing this but I thought it was clever and wanted to share since it directly answers your question.
EDIT
Just noticed you changed your answer. below may not apply anymore, but I'll leave it for future reference...
I would suggest having a separate child table for this.
STORES
auto increment ID
|
| the store name the store description etc..
| / / /
.--------------------------------------------------.
| id | name | description | etc |
|--------------------------------------------------|
| 1 | mary's kitchen | a fancy restaurant | etc |
| 2 | willow creek inn | we serve breakfast | etc |
'--------------------------------------------------'
STORE_HOURS
auto increment ID
| The STORES.id
| / the day (0-SUN, 6-SAT)
| _________/ / the 24h time OPEN (HH:MM:SS *TIME*)
| / _________/ ____/ the 24h time CLOSE (HH:MM:SS *TIME*)
| / / / /
.----------------------------------------------.
| id | store_id | day | time_open | time_close |
| 1 | 1 | 1 | 08:30:00 | 20:00:00 |
| 2 | 1 | 2 | 08:30:00 | 20:00:00 |
| 3 | 1 | 3 | 10:30:00 | 20:00:00 |
| 4 | 1 | 4 | 11:00:00 | 20:00:00 |
| 5 | 1 | 5 | 08:30:00 | 22:30:00 |
'----------------------------------------------'
Now, depending on what you want to display, you could query the table:
SELECT
stores.name AS store_name,
stores.description AS store_description,
store_hours.day AS store_hours_day,
TIME(store_hours.time_open) AS store_open,
TIME(store_hours.time_close) AS store_close
FROM
stores
JOIN
store_hours
ON
store_hours.store_id = stores.id
Result: http://sqlfiddle.com/#!2/e6872/8/0
With this table structure and relationship, you can then create granular queries without too much effort.
So this might be a hell of a response, but here is one way to do it... (Although I'm sure there must be more significantly better ways:
$day = date(l); // Day in full text representation.
$time = date(G); // current hour in 24 hour format.
$sql = "SELECT businessID FROM (SELECT SUBSTRING_INDEX(t_time,':',1) as start, SUBSTRING_INDEX(LEFT(t_time,POSITION('[' IN t_time) - 1), ':',-1) as end,businessID from (SELECT SUBSTRING_INDEX(SUBSTR(`column_date`,POSITION('$day' IN `column_date`) + LENGTH('" . $day . "') + 1),':',2) as t_time, businessID from `businessdetails ` where `column_date` like '%$day%') as t_table_1) as t_table_2 where start >= $time && end <= $time";
Hopefully that works =)
PS If you need help there are all these string functions you could use:
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html

Lost behind the logic of making a stats graphics from a mysql log

Thanks for reading.
This is not a coding question as much as it is a logic one. But if my current logic is wrong, some coding help would be appreciated.
I have made a table on my database which is a log of everything that happens on my site.
When a user registers, it's saved. When he logs, again. And so on. Each action is represented by a number.
The data looks like this
----------------------------
| id | action | timestamp |
----------------------------
| 1 | 1 | 1299132900 |
| 2 | 2 | 1346876672 |
| 3 | 14 | 1351983948 |
| 4 | 1 | 1359063373 |
----------------------------
ID and action are of type INT(11) and timestamp is TIMESTAMP
I'm using a query to retrieve all records from the last 30 days.
SELECT id, action, timestamp FROM log WHERE timestamp >= DATE_SUB( CURDATE(),INTERVAL 30 DAY)
It works, and gives me all the correct values.
I need to arrange this data to make a graphic in flot.
As I see it, there are 2 steps:
Group the results by action number.
Then, inside each group, separate values by date, so the X axis of the graphic is date and Y axis is count.
With those arrays I could make different javascript data arrys to pass to flot.
Am I on the right track?
Should there be several mysql queries, or a GROUP BY clause?
I'm kind of lost here and would appreciate any help.

Retrieving the three next times (in columns) occuring after now from a schedule table in mysql using php

I'm new at this so if you think this has been answered and could point me to the right article that would be great, I've looked, and I haven't found an answer, maybe it's just taken as given, who knows.
I'm trying to retrieve the next three times in a mysql table that occur after now for a given row.
e.g. a row looks something like this in the table.
IdNum , time1, time2, time3, time4, time5, time6, time7, etc.
if the current time is say 5:22 and it corresponds to a time after time3 but before time4, how can I query the table so that I get time4, time5 and time6, but not time7, time8 etc.
Thanks for taking the time to read my problem.
EDIT:
The table would be in the format as follows (where I have condensed it, there's going to be up to 100 columns, and probably as many rows)
| IdNum | Time1 | Time2 | Time3 | Time4 | Time5 | Time6 |
---------------------------------------------------------
| 1 | 3:22 | 4:10 | 5:10 | 6:25 | 7:23 | 8:24 |
---------------------------------------------------------
| 2 | 4:32 | 6:17 | 6:55 | 7:25 | 8:45 | 10:21 |
and so on, and then I would want to provide the query with IdNum = 2, and time = 5:22 and have it return row[0] = 6:17, row[1] = 6:55, row [2] = 7:25.
In my poorest ad-hoc, freehand, untested mysql query:
select * from table where times > 5:22 LIMIT 3
Some information you should read about with respects to MySQL:
LIMIT
Comparison Functions & Operators
note this was posted before the sample schema was posted.

Categories