I am trying to do, what I assume is, an easy task of adding days to a date.
I have a date stored in a MySQL table, in a column called meta_date, with the type of DATE (A date, supported range is 1000-01-01 to 9999-12-31)
I retrieve this date from the database as follows:
$thisId = 1;
$dateQuery = mysqli_query($connection, "SELECT * FROM `sometable` WHERE `id` = '$thisId'");
$fetchDate = mysqli_fetch_assoc($dateQuery);
$theDate = $fetchDate['meta_date'];
Now I add a number of days to this date.
$newDate = date("Y-m-d", strtotime($theDate . " + 7 days"));
Next I put it back inside the database with an UPDATE query.
$editDate = mysqli_query($connection, "UPDATE `sometable` SET `meta_date` = '$newDate' WHERE `id` = '$thisId'");
However the date always returns as 0000-00-00 after the update.
Am I missing something here to do with the way the date is handled in PHP?
edit: The data I first retrieve from the database (into $theDate) is "2016-11-30".
You can use Mysql's built in function DATE_ADD()
Syntext
DATE_ADD(date,INTERVAL expr type) Where date is a valid date expression and expr is the number of interval you want to add.
For your case
UPDATE sometable
SET `meta_date` = DATE_ADD(`meta_date` , INTERVAL 7 DAY)
WHERE `id` = '$thisId';
Related
I have data inserted into table 'dnt' with colum date being php datetime.
$date = time();// this was inserted into the db as :1481811673
$today = time();
"SELECT * FROM `dnt` WHERE 'date' = '$today'";
You cannot compare a timestamp with date today as timestamp changes per second so to compare right, you need to convert the timestamp stored in db into a dateformat and then compare that date with today date. You can do it as follows:
$today = date('Y-m-d'); // date today in format - YYYY-mm-dd
//your query
"SELECT * FROM `dnt` WHERE DATE_FORMAT(FROM_UNIXTIME(dnt.date), '%Y-%m-%d') = '$today'";
I hope it helps
This appears to answer your question http://www.tomjepson.co.uk/mysql-select-from-table-where-date-today/
tldr;
SELECT * FROM myTable WHERE DATE(myDate) = DATE(NOW())
Short and simple:
$stmt = "SELECT * FROM `dnt` WHERE 'date' = '".date('Y-m-d')."'";
To work with a timestamp:
$now = new DateTime();
$stmt = "SELECT *
FROM table
WHERE date = '".$now->getTimestamp()."'";
Detail
What the above query does is to SELECT all (*) FROM table dnt WHERE date =
the date() function in PHP returns a certain date based on the parameters you put in. the Y is for the years, the m for the months and the d for the days. So it will become date('Y-m-d') which will return 2010-01-01 for example.
the '". and ."' are to escape the php function so that it will not give you any syntax errors.
Besides what Peter said - the query is incorrect. You are comparing the date string value (date between single quotes) to a timestamp.
$stmt = "SELECT * FROM `dnt` WHERE `date` = '".date('Y-m-d')."'";
I have been trying for a while, read countless stackoverflow answers and still cant crack it!
I have a table in my db with a field called dob. This field is currently just a TEXT field (but i have since tried changing it to a DATE field and still cant get it to work).
The DOB field's data is in this format (UK dates) - 22/05/2016.
Im trying to find out the number of users who's birthdays are between two dates.
For example, anyone who was born in the last two years:
$twoyearsago=date('d/m/Y', strtotime("-2 years"));
$today = date("d/m/Y");
$sql = mysql_query("SELECT * FROM users WHERE dob >= '" . $twoyearsago . "' AND date <= '" . $today . "' ORDER by id DESC");
I also tried:
$sql = mysql_query("SELECT * FROM users WHERE dob BETWEEN '" . date('d-m-Y', strtotime($twoyearsago)) . "' AND '" . date('d-m-Y', strtotime($today)) . "'";
Hopefully you can see where me logic is and hoping you will see where im going wrong - any help would be appreciated.
Jack
With STR_TO_DATE can you convert your date
NOTE: i have changed the Column type from TIMESTAMP to DATE, because in a TIMESTAMP you can store date before 1970-01-01.
SELECT STR_TO_DATE('22/05/2016','%d/%m/%Y');
sample
MariaDB [bb]> SELECT STR_TO_DATE('22/05/2016','%d/%m/%Y');
+--------------------------------------+
| STR_TO_DATE('22/05/2016','%d/%m/%Y') |
+--------------------------------------+
| 2016-05-22 |
+--------------------------------------+
1 row in set (0.00 sec)
MariaDB [bb]>
so you can change you Table
ALTER TABLE `users`
ADD COLUMN new_dob DATE;
UPDATE `users` SET new_dob = str_to_date(dob,'%d/%m/%Y');
** Verify the dates
ALTER TABLE `users`
DROP COLUMN dob;
ALTER TABLE `users`
CHANGE COLUMN `new_dob` `dob` DATE;
** CREATE an INDEX for perfomance **
ALTER TABLE `users`
ADD KEY (`dob`);
SELECT
SELECT * from `users` where dob between '2014-01-01' AND `2015-08-01';
The problem with many local date formats is that their lexical and chronological order are different (eg, 16-11-2016 comes after 11-12-2016 lexically, but before chronologically). That's why storing dates in string fields in some regional format is in most cases a bad idea: you will get sorting issues sooner or later.
Next, when specifying dates literally for MySQL, you have to respect certain formats, as explained in the documentation
Putting that into practice, the range variables should look something like this:
$today = date("Y-m-d");
$twoyearsago=date("Y-m-d", strtotime("-2 years"));
Then we use a built-in function str_to_date to convert the string column into a date that can be compared correctly:
SELECT * FROM users WHERE
STR_TO_DATE(dob, '%d/%m/%Y') between '$twoyearsago' and '$today'
This will work, but in the long run you're much better off converting that dob column into a real date format (as #BerndBuffen shows) as it's clearer, easier to internationalize and a lot better performing.
Sidenote: you are still using the long-deprecated mysql_ extension. You should really switch to either mysqli_ or PDO.
You need to build your query by using actual date values, not string. So you need format YYYY-MM-DD in query - both side of the comparison.
Try following.
$twoyearsago=date('Y-m-d', strtotime("-2 years"));
$today = date("Y-m-d");
$sql = mysql_query("SELECT * FROM users WHERE STR_TO_DATE(dob, '%d/%m/%Y') >= '" . $twoyearsago . "' AND STR_TO_DATE(dob, '%d/%m/%Y') <= '" . $today . "' ORDER by id DESC");
STR_TO_DATE(dob, '%d/%m/%Y') makes sure your d/m/Y saved dob string value to be converted to date in the query that MySQL can understand and compare with the given YYYY-MM-DD values.
Actually the proper way is creating a date field and transferring dob string values as date to this new field by using the same function unless you will always get the date values as string into the dob field.
Another method is to use DateTime and format the date before doing your query.
$begin = '10/02/2014';
$emd = '10/02/2015';
$beginDate = DateTime::createFromFormat('d/m/Y', $begin);
$emdDate = DateTime::createFromFormat('d/m/Y', $emd);
$stmt = "
SELECT
...
FROM users
WHERE birthday >= '".$beginDate->format('Y-m-d')."'
AND birthday <= '".$endDate->format('Y-m-d')."'
";
In my database I stored date and time as a TIMESTAMP values. I want to retrive only today data from the database. This is code that I tried
$today = date("Y-m-d") . '00:00:00';
$last = date("Y-m-d") . '23:59:59';
$sql = "SELECT id, name, name2,some,some,submittimestamp,some FROM recs where submittimestamp Between $today AND $last";
$result = $conn->query($sql);
But I only get the 0 results message using this. There is more than 100 rows added today.
How can I solve this ? I cant change the database now. only way to solve this is change the PHP script
Do I need to convert PHP datetime to MYSQL timestamp ?
This is my sample database entry time-stamp value
2014-10-02 15:47:01
I only want to retrieve data for one day. time is not required !!
SELECT id, name, name2, submittimestamp
FROM recs WHERE submittimestamp > DATE_SUB(CURDATE(), INTERVAL 1 DAY);
Also you may try this, as DATE() ignores time part
SELECT id, name, name2, submittimestamp
FROM recs WHERE DATE(submittimestamp) = CURDATE();
I'm having a table named users in my MySQL database. There is a coulmn named user_reg_date(bigint(12)) in this table used to store the registration date for that user.
This column is storing the registration date in UNIX Timestamp format. I'm a newbie for this UNIX Timestamp and date manipulation in PHP.
Now my requirement is that I want to pass current date to a function and fetch the count of users whose registration date is current date(i.e. the count of users registered today).
I don't know how to pass the current date to the function and fetch the count of users who have their registration date as current date. I'm giving my PHP function code below.
/*The argument `$todays_date` I'm passing is dummy, please guide me how to pass the date also*/
function GetRegisteredUsersCount($todays_date) {
$sql = " SELECT count(*) as registered_users_count FROM ".TBL_USERS;
$sql .= " WHERE user_reg_date ='".$todays_date."' ";
$this->mDb->Query( $sql);
$data = $this->mDb->FetchArray(MYSQL_FETCH_SINGLE);
return $data;
}
Since your date is stored as an integer, you need to query using a range, between the start of today and up to (not including) the start of the next day.
$today = strtotime('today');
$tomorrow = strtotime('+1 day', $today);
$sql .= sprintf(
" WHERE user_reg_date >= %d AND user_reg_date < %d",
$today,
$tomorrow
);
See also: strtotime()
Btw, it's recommended to run this on a platform that uses 64-bit integers.
You should change user_reg_date(bigint(12)) field type to timestamp and set it default as CURRENT_TIMESTAMP. Whenever a new user will register it will automatically pick the current date time. And when you want to find out how many user registered today then just hit a query:-
$sql = "SELECT count(*) as registered_users_count from tb_users where datediff(CURDATE(),DATE(user_reg_date)) =0"
Would this be possible? I've used this to insert the date into a field called "date":
$date=date("m/d/y");
$sql="INSERT INTO pool (date) VALUES('$date' )";
$result=mysql_query($sql);
I've used this statement to get the date a week ago:
$variable = date('d-m-y', strtotime('-1 week'));
So how would I SELECT any rows which were added last week?
Instead of storing your dates as m/d/y, you should store them as Y-m-d :
$date=date("Y-m-d");
$sql="INSERT INTO pool (date) VALUES('$date' )";
In the database, you dates will then look like 2011-04-09.
That format is much easier to work with : alphabetical comparisons will work.
Which means that searching for rows that are older than a certain date would become something like this :
$variable = date('Y-m-d', strtotime('-1 week'));
$query = "select * from pool where date < '$variable'";
Also note that instead of working with a date field which is a varchar (or an equivalent) in your database, you could use a DATE column -- which would allow to to work with date and time functions in MySQL.
If the date field is a proper date type you can do < or > in your sql query. For example -
SELECT * FROM table WHERE date > '$date'
If you want everything from 1 week ago to now you can do something like the above or
SELECT * FROM table WHERE date BETWEEN '$date' AND NOW()