Selecting a datetime data and getting only the day? - php

I have a datetime column in my database and want to echo out how many users regisetered today.
id | register_date
1 | 2014-04-16 09:55:13
2 | 2014-04-14 19:23:49
$sql_users = "SELECT * FROM users";
$result_users = mysql_query($sql_users);
I thought that I could check every single data in it by using date('d', $register_time ) in a while statement. Is there any easier way to do it?

Use MySQL's DATE() and CURDATE() functions:
SELECT COUNT(*) FROM users WHERE DATE(register_date) = CURDATE()

Related

How to check if user have X records from last 1 hour? [PHP/MySQL]

I want to check if the user has 5 records in my MySQL database in the last hour. That´s how I am doing it now:
$link = mysqli_query($link, "SELECT * FROM find_points WHERE timestamp > '.time()-3600.' AND user_id = '1' ORDER BY id DESC");
if(mysqli_num_rows($link) >= 5) {
echo 'more than 5 results';
}
It looks like it should work, but it doesn't work...
Please use below query
SELECT * FROM find_points WHERE TIMESTAMPDIFF( hour, timestamp , now() ) > 1 AND user_id = '1' ORDER BY id DESC
You can read in manual about TimestampDiff
It can be used to run difference between 2 dates in various formats.
Please check the Demo on SqlFiddle
It shows how TimestampDiff returns result and you can use the same in WHERE clause.
Update
Based on your comment, that the timestamp is stored as Unix Timestamp, you could use the following query:
SELECT * FROM find_points WHERE TIMESTAMPDIFF( hour, FROM_UNIXTIME(timestamp) , now() ) > 1 AND user_id = '1' ORDER BY id DESC
FROM_UNIXTIME will convert your UNIX Timestamp to DateTime Format. You can then pass this to TIMESTAMPDIFF which will calculate difference and return the number of hours.
Hope this helps.
"SELECT * FROM find_points WHERE timestamp > DATE_ADD(NOW(), INTERVAL 1 HOUR) AND user_id = '1' ORDER BY id DESC"

postgresql query in comparing dates with duration stored in other column

I have a table like
------------------------------
id | created_date | duration
------------------------------
duration is no.of days, now I want to select records that are created_date(timestamp)+duration(integer) > current time
I tried this in my where clause
"select * from table where (created_date + duration days) > now()"
now resultset is empty, I have records that should come out for my requirement, I suspect my query is not right, help me get it right.
Very close. I would do this as:
select *
from table
where created_date > now() - duration * interval '1 day'

event schedule php MySQL keeping track of upcoming events

i have been working on event schedule with php and MySQL my goal is to be able to have the background of a website change for each event such as Halloween Christmas and so on i have come up with one that will work with the month but i am needing it to workout the day to ignoring the year
<?php
$con = mysql_connect(MYSQL_host,MYSQL_username,MYSQL_password);
mysql_select_db(MYSQL_Database, $con);
$result = mysql_query('SELECT * FROM Event_Schedule WHERE MONTH(Start) <= MONTH(NOW()) AND MONTH(End) >= MONTH(NOW())') or die('Query failed: ' . mysql_error());
$Edit_theme_row = mysql_fetch_array($result)
?>
i have tried adding Day in to the code
$result = mysql_query('SELECT * FROM Event_Schedule WHERE (MONTH(Start) <= MONTH(NOW()) AND DAY(Start) <= DAY(NOW())) AND (MONTH(End) >= MONTH(NOW()) AND DAY(End) >= DAY(NOW()))') or die('Query failed: ' . mysql_error());
$Edit_theme_row = mysql_fetch_array($result)
?>
But seem to ignore event
using template DATE in MySQL
example
2015-10-28 to 2015-11-02 halloween
2015-12-01 to 2015-12-26 christmas
ignoring the year so each year it will change on that month and day
i hope that i understand your problem correctly. The first thing i have seen is that you use functions in the WHERE on the database fields. This is not a good idea. So MySQL must read every record (FULL TABLE SCAN) to do this and cant use an index for this.
The second thing is that you not normalize the start and end date of each event in 2 separate fields to do an easy compare. You can store the dates from the application in second fields with an normalized year ie. '1970' so you can easy compare it or you use PERSISTENT fields in MySQL then MySQL can do it for you.
Here a Sample
CREATE TABLE `table1` (
`nr` int(11) unsigned NOT NULL AUTO_INCREMENT,
`event_name` varchar(32) DEFAULT NULL,
`event_start` date NOT NULL DEFAULT '0000-00-00',
`event_end` date NOT NULL DEFAULT '0000-00-00',
`norm_start` date AS ( date_format(event_start,'1970-%m-%d') ) PERSISTENT,
`norm_end` date AS ( date_format(event_end,'1970-%m-%d') ) PERSISTENT,
PRIMARY KEY (`nr`),
KEY `event_start` (`event_start`,`event_end`),
KEY `norm_start` (`norm_start`,`norm_end`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Now we insert a row
INSERT INTO `table1`
( `event_name`, `event_start`, `event_end`)
VALUES
('hallo', '2015-10-31', '2015-10-31');
The Reseult
MariaDB > select * from table1;
+----+------------+-------------+------------+------------+------------+
| nr | event_name | event_start | event_end | norm_start | norm_end |
+----+------------+-------------+------------+------------+------------+
| 4 | hallo | 2015-10-31 | 2015-10-31 | 1970-10-31 | 1970-10-31 |
+----+------------+-------------+------------+------------+------------+
1 row in set (0.00 sec)
Now you can directly compare the dates
SELECT *
FROM table1
WHERE date_format(now(),'1970-%m-%d')
BETWEEN norm_start AND norm_end;
So you can the events. The only thing is when a event overlaps a year ( 2015-12-30 - 2016-01-07 ) you mus put 2 rows in the eventtable.
Please let me now if this wars what you want

Count records this month

I have a table that stores dates in the format of MM/DD/YY (field name is date). I need to have a count that totals just the records for the current month. From searching, this is what I currently have but something is not right. Do I need to do a convertToDate, is it that my field is called "date", or am I missing something entirely?
$totalcount = mysql_query("select count(*) as 'total'
FROM state_to_state
WHERE status = 99 AND type = 1
AND MONTH(`date`) = MONTH(CURDATE())
AND YEAR(`date`) = YEAR(CURDATE())");
$totalnum = mysql_fetch_array($totalcount);
if($totalnum['total'] > 0) { $month_status = $totalnum['total']." this Month. "; }
Your dates are NOT native mysql dates (varchar, probably?), so you cannot use the mysql date functions on them directly. date('MM/DD/YY') will not work reliably:
mysql> select month('03/03/14'), month('03/18/14');
+-------------------+-------------------+
| month('03/03/14') | month('03/18/14') |
+-------------------+-------------------+
| 3 | NULL |
+-------------------+-------------------+
Convert your date fields to native mysql date types, or take a huge hit on performance and convert them to native date values onthefly via str_to_date().

Calculate subtracts date in mysql for birthday event

i create a event for calculate a birthday , for example:
birthday date = 1990-09-07
now date = 2013-09-05
my query :
SELECT id FROM user WHERE ( birthday - NOW() ) <= 7
this query is mistake
I think DAYOFYEAR function is more suitable for you:
mysql> SELECT DAYOFYEAR('2000-09-07') - DAYOFYEAR(now()) AS diff;
+------+
| diff |
+------+
| 3 |
+------+
Today is 2013-09-05, it gave 3 days. Now you can compose the condition. Please, mind 1 day in the leap year.
You said its for birthday so you must consider month and date as date can be repeat for every month..
So try something like below, for year difference.
SELECT
(YEAR(birthdate) - YEAR(NOW())) AS yeardifference
FROM
table
WHERE
MONTH(birthdate) = MONTH(NOW())
AND
DATEDIFF(birthdate, NOW()) <= 7
For day difference
SELECT
DATEDIFF(birthdate, NOW())
FROM
table
WHERE
MONTH(birthdate) = MONTH(NOW())
AND
DATEDIFF(birthdate, NOW()) <= 7
The Dayofyear function would be useful, just to put it in context with your requirement
SELECT id FROM user WHERE (DAYOFYEAR(birthday) - DAYOFYEAR(NOW())) <= 7
I think your query should be something like
SELECT id
FROM user
WHERE ( DAYOFYEAR(birthday) - DAYOFYEAR(NOW()) <= 7)

Categories