How to Get Where 'Column + 7 Days' >= NOW in PHP - php

I have a problem. Maybe this question is very stupid, but I've been searching everywhere and not getting what I want.
I will immediately delete my post, if I get the answer.
I've a table like this:
ID | Title | Date
-----------------------------
1 | AAA | 2019-03-25
2 | BBB | 2019-03-21
3 | CCC | 2019-03-23
I've tried this:
function get_all() {
$plusdays = strtotime('+7 day');
$now = date('Y-m-d H:i:s');
$this->datatables->select('*');
$this->datatables->from('atable');
$this->datatables->where('crt_date + INTERVAL 7 day >=', $now);
return $this->datatables->generate();
}
How I can show table like this:
ID | Title | Date
-----------------------------
2 | BBB | 2019-03-21
So I want to show data created on a certain date and expire if more than 7 days after the data was created. Or are there other ideas?
do I have to add the expired date column?
Thanks

Here's an SQL query that should work (and no, it's not necessarily the most elegant one):
SELECT *
FROM atable
WHERE (UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(date)) >= (60 * 60 * 24 * 7);
I presume you can translate that appropriately to your PHP code. Basically, I'm getting the difference in seconds between now() and the stored date then I'm seeing if the difference is greater than or equal to seven days.

I decided to add one more column is exp_date for easier use in the future.
Code like this:
$date = time();
$date_exp = date('Y-m-d H:i:s', strtotime('+7 day', $date));
Thanks everyone!

Tip Don't use function or eval in column at where (performance problem)
In this case you must subtract $now by 7 day and
$this->datatables->where('crt_date >=', $theDateBefore7Day);

Related

Get month difference only if the days are the same

How can I get the difference of months between two dates in MySQL only if the days are the same? Here is what i have so far but it doesn't work because when the days are not the same, it still works:
TIMESTAMPDIFF(MONTH, '2019-05-05', '2019-06-05')
Output: 1
TIMESTAMPDIFF(MONTH, '2019-05-05', '2019-06-22')
Output: 1 // should NOT work because days are 05 and 22. Needs to be the same dates
I can obviously do:
DAY('2019-05-05') = DAY('2019-06-05') AND TIMESTAMPDIFF(MONTH, '2019-05-05', '2019-06-05')
but how can I do it in one function?
Thanks!
SUBDATE()/ADDDATE/DATE_SUB/DATE_ADD will handle this well:
SELECT DATE_SUB('2019-06-22', INTERVAL 1 MONTH) = '2019-05-05'
| DATE_SUB('2019-06-22', INTERVAL 1 MONTH) = '2019-05-05' |
| ------------------------------------------------------: |
| 0 |
SELECT DATE_SUB('2019-06-22', INTERVAL 1 MONTH) = '2019-05-22'
| DATE_SUB('2019-06-22', INTERVAL 1 MONTH) = '2019-05-22' |
| ------------------------------------------------------: |
| 1 |
See the DBfiddle
In MySQL, you can get it by using the below query...
select DATEDIFF('2019-06-22', '2019-05-05') as Diff from table_name where
day('2019-06-22') == day('2019-05-05');
using column name...
select DATEDIFF(dateColum2, dateColum1) as Diff from table_name where
day(dateColum2) == day(dateColum1);
From PHP you can get it like below...
$dateValue1 = '2019-05-05';
$dateValue2 = '2019-06-22';
$time1=strtotime($dateValue1);
$day1=date("D",$time1);
$time2=strtotime($dateValue2);
$day2=date("D",$time2);
if($day1 == $day2 ) {
$seconds_diff = $time2 - $time;
}

Symfony: DQL select between date

I'm trying to select from my SQLite table all the rows in selected months and sum the value in "total" column.
Here is my example table:
| ID | DATE | TOTAL |
| 1 | 22-11-2017 | 700 |
| 2 | 26-11-2017 | 100 |
| 3 | 28-11-2017 | 150 |
| 4 | 30-11-2017 | 50 |
Here is the dql function
public function getDataByMonth($repo, $year, $month)
{
date = new \DateTime("{$year}-{$month}-01 00:00");
$dateEnd = new \DateTime("{$year}-{$month}-31 23:59");
$query = $qb->where('b.date BETWEEN :start AND :end')
->setParameter('start', $date->format('d-m-Y H:i'))
->setParameter('end', $dateEnd->format('d-m-Y H:i'))
->select('SUM(b.total) as totals');
}
Even if the query goes, when I set $monthvariable to October (so 10) the query return 1000instead of NULL.
I'm calling the function using
$earnings = $this->getDoctrine()->getManager()->getRepository(Invoices::class);
$this->getDataByMonth($earnings,date("Y"), strftime("%m", strtotime("-1 months")));
What I'm doing wrong?
I need to select the right rows relating to the selected month.
maybe you should try sth like this, had similar problem and it worked:
->add('where', $qb->expr()->between(
'e.datetimefield',
':from',
':to'
))
it's database software independent, should work with most databases, more info in doctrine documentation:
http://docs.doctrine-project.org/en/latest/reference/query-builder.html#the-expr-class
and also don't format datetime object, ex:
$from = new \DateTime();
->setParameter('from', $from);
SQLite does not have a storage class set aside for storing dates
and/or times. Instead, the built-in Date And Time Functions of SQLite
are capable of storing dates and times as TEXT, REAL, or INTEGER
values
--https://sqlite.org/datatype3.html
So I don't think you can use BETWEEN.
I had similar issue with SQLite I ended up using timestamp
Symfony 3 ?
$date = new \DateTime("{$year}-{$month}-01 00:00");
$dateEnd = new \DateTime("{$year}-{$month}-31 23:59");
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery("SELECT SUM(p.total) FROM AppBundle:Invoices p WHERE p.date >= :dateFirstDay and p.date <= :dateLastDay")
->setParameter('dateFirstDay',$date->format('d-m-Y H:i'))
->setParameter('dateLastDay',$dateEnd->format('d-m-Y H:i'));

Delete items from database with more than x days in CodeIgniter/PHP

Can anyone tell me how to delete items from a table with more than 5 days in CodeIgniter please? I searched here and on google and can't find anything that works.
EDIT:
My table in database looks like this:
| ID| Name | CreationDate |
| 1 | Test | 01-12-2014 |
| 2 | Test2| 01-11-2014 |
and so on, I hope you understand me.
Steps:
Get the current date
Calculate the date 5 days ago
Delete the items from the database where the CreationDate is less than (older than) 5 days
Code:
$date = date("Y-m-d H:i:s",time());
$date = strtotime($date);
$min_date = strtotime("-5 day", $date);
$this->db->where("CreationDate < '$min_date'", NULL, FALSE);
What is the type of CreationDate? What do you mean by more than 5 days?
If you mean you want to delete items where CreationDate is older than 5 days, and CreationDate type is string (varchar), you could use this:
$this->db->query("DELETE FROM MyTable where STR_TO_DATE(CreationDate, '%d-%m-%Y') < DATE_SUB(NOW(), INTERVAL 5 DAY)";
But if CreationDate type is mysql date, then simply use:
$this->db->query("DELETE FROM MyTable where CreationDate < DATE_SUB(NOW(), INTERVAL 5 DAY)";

MYSQL query for every hour

$today = mktime(0,0,0);
$yesterday = $today - 86400;
$this->view->numberyesterday=$db->fetchAll("SELECT * FROM `transactions` WHERE `siteid`=".$sid." AND `timestamp` > ".$db->quote($yesterday,'integer')." AND timestamp < ".$db->quote($today,'integer'));
I have used the above code to display all the records of yesterday. Now I need to plot the graph for each hour. How can I retrieve the records in every hour from the above query?( like, records within 12-1 AM, 1-2 AM....23-24PM etc)
Thanks!
Edit:
I wish I could store the records of each hour in each variable. So that there will be 24 variable for 24 hours. So it is easy to draw the graph.
You did not specify how the output would look like, but it seems like this construct would help you:
select Hour(timestamp) transhour, count(*) transcount
from transactions
where yourfilters = yourvalues
Group by Hour(timestamp)
The output will look like this:
transhour | transcount
======================
0 | 2
1 | 23
2 | 45
3 | 23
... | ...
22 | 34
23 | 3
Warning: if no transactions were performed in a given hour, the output will omit this hour (and not bring it back with count zero)

mysql select month from timestamp

I have a mysql query but it's not working properly yet. The idea is: I have a month calendar, so I select all items with the current month form my db.
I select TV show episodes, they air on a specific date but they are available the next day. I want to have the available dates in my cal. So a specific example: An episode aires 2013-03-31 and is available on 2013-04-01. This episode will not be selected from the db. I have tried something like this:
$this->db->where('MONTH(FROM_UNIXTIME(first_aired+86400))='.$month);
But it didn't work. Does anyone know a solution? This is my full code:
$this->db->select('*, episodes.overview as overview, episodes.id as ep_id, shows.id as id');
$this->db->from('episodes');
$this->db->join('shows', 'episodes.imdb_id = shows.imdb_id');
$this->db->where('CHAR_LENGTH(episodes.ep_title) > 1');
$this->db->where('MONTH(FROM_UNIXTIME(first_aired))='.$month);
$this->db->where('YEAR(FROM_UNIXTIME(first_aired))='.$year);
$this->db->order_by('episodes.first_aired', 'DESC');
$data = $this->db->get()->result_array();
Thanks in advance!
Use MySQLs DATE_ADD function:
select mydate, date_add(mydate, interval 1 day) from testdata;
So if you want to get the month of the next day, use month(date_add(...))
mysql> select mydate, date_add(mydate, interval 1 day) "next day", month(date_add(mydate, interval 1 day)) "month of next day" from testdata;
+------------+------------+-------------------+
| mydate | next day | month of next day |
+------------+------------+-------------------+
| 2013-01-31 | 2013-02-01 | 2 |
| 2013-01-01 | 2013-01-02 | 1 |
+------------+------------+-------------------+
2 rows in set (0.00 sec)
So for your query, use something like $this->db->where('MONTH(DATE_ADD(first_aired, INTERVAL 1 DAY))='.$month);. Oh, and you might have to add a FROM_UNIXTIME here and there.

Categories