I am trying to insert a future date into a MySQL table from PHP. I have been able to insert the current date using strtotime but when I add time to this call it does not seem to insert it. Here is the code:
<?php
$currentDate = strtotime('now');
$expirationDate = strtotime('+ 90 days');
include_once "mysql-connect.php";
$cur = "UPDATE table SET current_date = FROM_UNIXTIME($currentDate) WHERE ...";
if (!mysql_query($cur,$con))
{
die('Heres Your Error: ' . mysql_error());
}
echo "the date is set";
$exp = "UPDATE table SET expiration_date = FROM_UNIXTIME($expirationDate)
WHERE ...";
if (!mysql_query($exp,$con))
{
die('Heres Your Error: ' . mysql_error());
}
echo " expiration date is set";
mysql_close($con)
?>
Like I said, when I run this it will insert the current date into the current_date row as requested. For some reason it will not insert expiration_date which is 90 days in front of the current date. I have verified that the expiration date is being picked up as 90 days in the future. Why is this not working?
You can do it in MySQL directly:
$days = 90;
$sql = "UPDATE ... SET expiration_date = DATE_ADD(current_date, INTERVAL $days DAY);"
which'll save you the excess round-tripping from datetime->unix timestamp->datetime.
It is a bad idea to use strtotime() function because it does not always work nicely.
Rather than doing dates in PHP, I'd suggest you do them directly in MySQL that provides a decent pool of date-time functions - http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html.
For your query, you can do:
UPDATE `table`
SET `current_date` = NOW(), `expiration_date` = DATE_ADD(NOW(), INTERVAL 90 DAY)
WHERE ...;
By the way, for your query case, does the second UPDATE return any errors. Which part of the following IF executes?
Related
I am a beginner in PHP and Javascript, so I'm struggling to compare two dates in a SELECT request like this:
<?php
require 'db.php';
$sql = "SELECT * FROM shortcode WHERE invalid_from_shortcode < Date()";
$result = pg_query($sql);
if (!$result) {
echo "Problem with query " . $query . "<br/>";
echo pg_last_error();
exit();
}
?>
I'm trying to select only the 'shortcodes' where the [invalid_from_shortcode] column is inferior from the current date.
I don't know how to get the current date and whether the structure is correct.
<?php
require 'db.php';
$sql = "SELECT * FROM shortcode WHERE invalid_from_shortcode < NOW()";
$result = pg_query($sql);
if (!$result) {
echo "Problem with query " . $query . "<br/>";
echo pg_last_error();
exit();
}
?>
Date() is a php function. in Mysql/PostgreSQL you must use NOW()
...
$sql = "SELECT * FROM shortcode WHERE invalid_from_shortcode < Date()";
...
A PHP functions like Date() is not visible in the SQL string. Either pass a value or use an equivalent Postgres function, like #pr1nc3 already suggested.
However, while you do not disclose the actual data type of invalid_from_shortcode it's unclear whether now() can serve as equivalent function. It returns the current timestamp with time zone, which is meaningfully different from the current date - effectively equivalent to the current timestamptz truncated to 00:00 according to the current timezone setting. You might need CURRENT_DATE (same as now()::date) instead. Related:
Select today's (since midnight) timestamps only
Aside: Unlike two other answers suggested, there is no CURDATE() in Postgres. That probably confusing MySQL with Postgres.
You want to use NOW() not DATE().
May be you are looking for CURDATE() .
$sql = "SELECT * FROM shortcode WHERE DATE(invalid_from_shortcode) < CURDATE()";
You should be using NOW() function instead of date() and you need to convert the date in a suitable format enter link description here you can visit this link for converting the date format
use
NOW() Returns the current date and time
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';
$newtime = date("Y-m-d H:i:s", time() + 600);
mysql_query("UPDATE rounds SET clock = $newtime WHERE `round`='$CurrentRound' ") or die(mysql_error()); //update DB
This code is failing to add the current time (+10 mins) to the MySQL database.
The cell in the database is datetime format.
I had done this before, but upon rewriting the code, it has stopped working.
You could use
UPDATE rounds SET clock = NOW() + INTERVAL 10 MIN WHERE round = '$CurrentRound'
To set the clock to 10 mins, per the time on the MySQL server.
Alternatively, you need to add ' around the $newTime variable
UPDATE rounds SET clock = '$newtime' WHERE round = '$CurrentRound'
change your query to this:
("UPDATE rounds SET `clock` = '$newtime' WHERE `round` = '$CurrentRound'")
I need to test current time against a datetime from database, if it has been 30 mins then execute code, if not then dont. This is where I am at and I am stuck:
$link = mysqli_connect("hostname", "username", "password", "database");
$q = "SELECT id FROM dwCache ORDER BY id DESC LIMIT 1";
$qu = mysqli_query($link, $q);
while($row=mysqli_fetch_array($qu, MYSQL_ASSOC)){
$id = $row['id'];
$cache = $row['cache'];
$timest = $row['time'];
}
$newTime =
$difference = $timest
if($timest >= )
As you can see towards the bottom I lose it as I am not sure what to do.
$timest returns : 2013-02-01 12:36:01 as the format Y-m-d h-i-s
Apologies on double post, other deleted.
First convert $timest to timestamp
$time = strtotime($timest);
$curtime = time();
if(($curtime-$time) > 1800) { //1800 seconds
//do stuff
}
do it all in sql statement
SELECT id FROM `dqCache` WHERE `time`<DATE_SUB(NOW(), INTERVAL 30 MINUTE);
This will return everything from your table where the time column is before 30 minutes before now.
I like to use unix timestamps in this situation.
$timest = date('u'); // gets the unix timestamp
$q = "SELECT id
FROM `dwCache`
WHERE {$timest} - UNIX_TIMESTAMP(`timestamp_col`) > 1800";
Explanation:
This basically calculates the difference between the current time and the time in the table column. If it's higher than 1800 (30 minutes), it will select the row, and your PHP code will be executed.
Advantages
There are some advantages to using this instead of the PHP check you started doing. You will select fewer rows, thus occupy less memory.
PS:
Thumbs up for using MySQLi !
SELECT id FROM dwCache ORDER BY id DESC LIMIT 1
you'll get only id field, it's the first.
The second, for time converting: MySQL convert datetime to Unix timestamp
Third: you can convert your time string using strtotime function.
I've seen lots of threads about date ranges in MySQL but I still don't seem to be able to find an answer for what I'm looking for so any help will be greatly received.
I have a MySQL table with 3 columns, date - startTime - finishTime. The date is a MySQL 'date' type field and the start and finish times are both 'time' type fields.
Say for example I have an entry in the database as follows, lets call this session 1;
date = 2011-06-30, startTime = 09:00:00, finishTime = 11:00:00
If I come to add another session I need to make sure that it doesn't conflict with an existing session. So the following would fail because it falls in between session 1 start and finish times.
date = 2011-06-30, startTime = 10:00:00, finishTime = 12:00:00
So the record can only be inserted 'AFTER' or 'BEFORE' an existing session.
I'm using PHP/MySQL and am going on the basis that a query can be run and if there 'are' matching results then, fail, if there 'arent' matching results then insert.
Thanks in advance.
I'm using PHP/MySQL and am going on the basis that a query can be run and if there 'are' matching results then, fail, if there 'arent' matching results then insert.
Well, try this. Here :date: is the date of the entry you are going to add, and :start-time: and :finish-time: are its start and finish times respectively.
SELECT EXISTS (
SELECT
1
FROM
TableName
WHERE
`date` = :date: AND
( :start-time: BETWEEN startTime AND finishTime OR
:finish-time: BETWEEN startTime AND finishTime OR
startTime BETWEEN :start-time: AND :finish-time:
)
) AS `Clash`
I faced this problem of date overlapping detection, my first idea was to do something like Hammerite's solution but i found this solution incomplete mainly because there are too many possible scenarios where two date ranges can be in conflict:
The query I ended up using to solve this was something like:
/* overlapping dates */
SELECT *
FROM my_table
WHERE `date` = $date AND
NOT (
`start_time` < $start_time and `finish_time` < $start_time
OR
`start_time` > $end_time and `finish_time` > $end_time
)
For more details you can check my blog here
I would structure the table in a different way. I'd have two columns, both datetime type, named session_start and session_end.
Logic is: you cannot insert new session if it's session_start time isn't > or < than old session session_end.
Assuming $date, $startTime and $finishTime are your PHP variables that store the date, start time and finish time respectively to be inserted.
$query = 'INSERT INTO `session`
SELECT \'' . $date . '\', \'' . $startTime . '\', \'' . $finishTime . '\'
FROM `session`
WHERE NOT EXISTS (SELECT *
FROM `session`
WHERE `date` = \'' . $date . '\'
AND \'' . $startTime . '\' BETWEEN `startTime` and `finishTime`
)';
Hope this helps.
I would use the simple:
INSERT INTO session
( `date`, startTime, finishTime )
SELECT
( $date, $startTime, $finishTime )
WHERE NOT EXISTS
( SELECT
*
FROM
session
WHERE
`date` = $date
AND $startTime < finishTime
AND startTime < $finishTime
)
The < should be changed to <= if you want the two periods 09:00 - 11:00 and 11:00 - 13:00 to collide.