Date wrong in PHP function - php

I have the following code and I'm able to add to today's date, but if the existing date is before today it still returns today's date. MySQL data is stored as a y-m-d string.
$date = date('Y-m-d');
$oldate = "SELECT date FROM signup WHERE user='$user'";
$result1 = mysqli_query($connection, $oldate) or die(mysqli_error($connection));
if (strtotime($result1) < $date) {
$date1 = date('Y-m-d', strtotime("+$months months", strtotime($date)));
} else {
$date1 = date('Y-m-d', strtotime("+$months months", strtotime($result1)));
}

You are comparing timestamp value ($result1) with string $date1.You need to cast your $date1 to timestamp as well. Change your if condition to make it work as follow:
if(strtotime($result1)<strtotime($date))
{
....
}
else
{
.....
}

The reason you're above code isn't working is because $result1 won't be a date. mysqli_query will return an instance of mysqli_result when you've performed a successful select query.
http://php.net/manual/en/mysqli.query.php :
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.
You can use mysqli_fetch_assoc to get the information you want:
$row = mysqli_fetch_assoc($result1);
$rowDate = $row['date'];
Also, as Prada pointed out you can't not compare dates in the way you have in your question, however, you could do something like:
if (strtotime($rowDate) < strtotime($date))
Alternatively, you could use DateTime and have something like:
$oldate = "SELECT date FROM signup WHERE user='$user'";
$result1 = mysqli_query($connection, $oldate) or die(mysqli_error($connection));
$row = mysqli_fetch_assoc($result1);
$now = new DateTime;
$date = new DateTime($row['date']);
$date1 = $date < $now
? $now->modify("+$months months")->format('Y-m-d')
: $date->modify("+$months months")->format('Y-m-d');
Hope this helps!

Related

PHP strtotime returning an integer, messing up date calculation

I am trying to find the difference between two datetime objects, in this case the difference between the current date ($nowDate) and the result I've pulled from a datetime column in MySql ($row['dueDate]' , or $rowDate). I have set the value in MySql to datetime and I am trying to subtract that time I pull by the current date as represented as a DateTime object. The problem is that I have tried to convert what I get from MySQL into a DateTime object but
I've tried first using the ::createFromFormat option to try to wrangle the sql output into a usable format, but a php error is thrown claiming the result is a boolean. When I try using strtotime the error thrown claims it is an integer, and when I try to use the output from the program PHP claims it's a string!
Code below:
<?php
$mysqli = mysqli_connect('127.0.0.1','root','', 'taskdb'); //open connection
//retrieve variables
$sql = "SELECT * FROM tasklist WHERE completion_flag = FALSE"; //
$sqldata = mysqli_query($mysqli,$sql) or die('error retrieving data');
//Display results
echo "<table>";
echo "<tr><th>Task</th><th>Type</th><th>Due Date</th>";
$counter = 0; //may need to make global, not sure
$results = array();
while($row = mysqli_fetch_array($sqldata, MYSQLI_ASSOC)){
//store each row as variables
var_dump($row['dueDate']);
if ($row['externalFlag'] == 1) {
$E = 1;
} else{
$E = 0.5;
}
//days until completion
date_default_timezone_set('America/Vancouver');
//$nowDate = date("Y-m-d H:i:s");
$nowDate = new DateTime;
var_dump($nowDate); //tests positive- outputting current time
$rowDate = strtotime($row['dueDate']); //WHY ISN'T THIS GIVING ME A DATETIME TYPE???
$D = 1 / (date_diff($nowDate, $rowDate)); //ERROR
//supposed to put the most recent date first!
How do I get the $rowDate variable to be of the dateTime type and not something else?
The date_diff() needs two DateTimeInterface objects as arguments.
$nowDate = new DateTime ;
$rowDate = new DateTime("2018-01-05") ;
$diff = date_diff($nowDate, $rowDate) ;
Then $diff is now a DateInterval, not a numeric value. But you can use seconds or microseconds, by example :
$seconds = $diff->s ; // integer value
$microseconds = $diff->f ; // float value

Can't insert string or datetime objects to mysql

I want to insert two datetime's into mysql.
$taskcompdate is a user written string that needs to be converted into a datetime object and formatted with a "d/m/y" format.
The second, $datenow is simply the now time.
The insert query works, but all dates in all records are displayed as 0000-00-00 00:00:00
I tried every possible way I found, but none works. What am I doing wrong?
<?php
$conn = mysqli_connect("127.0.0.1", "root", "", "todo_list");
$taskname = $_POST["taskname"];
$taskcompdate = $_POST["taskcompdate"];
$datenow = date("H:i:s d/m/y");
$insert_date1 = date('d/m/y', strtotime($taskcompdate));
$insert_date2 = date('H:i:s d/m/y', strtotime($datenow));
$sql_main = "INSERT INTO task_main (task, complete_date, added_date) VALUES ('$taskname', '$insert_date1', '$insert_date2')";
$result = mysqli_query($conn, $sql_main);
if ($result) {
echo 'success';
} else {
echo 'failure' . mysqli_error($conn);
}
?>
Your dates are in an invalid format for MySQL's date and datetime types. They must be in YYYY-MM-DD HH:MM::SS format.
$insert_date1 = date_format($taskcompdate, "Y-m-d");
$insert_date2 = date('Y-m-d H:i:s', strtotime($datenow));

Why does MySQL say 'Unsupported operand types' when checking for existence of a date in my query?

I have the following code and I want to take the timestamp stored in $begin and pass it to a MySQL query, but the query is failing with:
Fatal error: Unsupported operand types
Here's the code used to populate the variable $begin:
$datepicker_begin = "01/07/2013";
$begin = DateTime::createFromFormat('m/d/Y', $datepicker_begin);
$beginObj = $begin->format('Y-m-d');
$begin = strtotime($beginObj); // becomes Unix Timestamp
Here is the code for the query. It's checking the date column which is a date type and is called date, to see if the date exists in the table.
// Check if chosen date is available.
$s=$dbh->prepare("
SELECT DISTINCT
`date`
FROM
`report_coa_bal_hist`
WHERE
UNIX_TIMESTAMP(date) = ?
");
if ($s->execute($begin)) {
return true;
} else {
return false;
}
strtotime creates date in unix timestamp
you have to directly use this variable without doing strtotime on it
$begin = strtotime($beginObj);
Edit
Use this query with ` around date
$s=$dbh->prepare("
SELECT DISTINCT
`date`
FROM
`report_coa_bal_hist`
WHERE
UNIX_TIMESTAMP(`date`) = ?");
if ($s->execute($begin)) {
return true;
} else {
return false;
}
Your current code should work fine ... but alternatively you can try this
$datepicker_begin = "01/07/2013";
$begin = DateTime::createFromFormat('m/d/Y', $datepicker_begin);
echo $begin = $begin->getTimestamp();; // becomes Unix Timestamp
Have a look http://php.net/manual/en/datetime.gettimestamp.php
Try FROM_UNIXTIME:
$datepicker_begin = "01/07/2013";
$begin = DateTime::createFromFormat('m/d/Y', $datepicker_begin);
$beginObj = $begin->format('Y-m-d');
$begin = strtotime($beginObj); // becomes Unix Timestamp
$sql = "INSERT INTO test(ID, time) VALUES(NULL, FROM_UNIXTIME('$begin'));";
mysql_query($sql);

Failing to compare php date with mysql date

Got stuck in a complex or maybe stupid problem. I am getting a query from mysql, and then trying to compare a date column with a PHP data which i formatted to the same format i.e "Y-m-d" it always results in no match, although i see there is a match.. and it gets the right result set too.
<?php
date_default_timezone_set('America/Los_Angeles'); // set timezone to our timezone
$constantTime = time(); // get value of time in constant
$appDate = date("Y-m-d", $constantTime); //that defines php time variable -
$queryDate = "SELECT * FROM date WHERE date='$appDate'";
$resultDate = mysql_query($queryDate) or die("Sorry Website Under Maintainence");
$recordDate = mysql_fetch_array($resulDate);
if ($appDate == date("Y-m-d", strtotime($recordDate['date']))) {
echo "MATCH ";
$dateID = $recordDate['dateID'];
} else {
mysql_query("insert into date(date) values('$appDate')")or die("Database write error1");
$resultDate = mysql_query($queryDate) or die("Sorry Website Under Maintainence");
$recordDate = mysql_fetch_array($resultDate);
echo "NO MATCH ";
$dateID = $recordDate['dateID'];
}
This is always triggering the else, i tried === instead of ==, i tried strcmp
As i assume you're comparing datetime field, you have two possibilities:
Cast field to date:
$queryDate = "SELECT * FROM your_table WHERE date(your_date_field) = date('$appDate')";
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_date
or
Modify your date format to be ISO compatible:
$appDate = date("Y-m-d H:i:s", $constantTime); //it defines date in format 2015-03-14 15:00:00
$queryDate = "SELECT * FROM your_table WHERE your_date_field='$appDate'";
See also this question

MYSQL Date range query not working correctly

I have a problem getting certain data from my database by querying a date range. In my database i have a DATE type field within the format YYYY-MM-DD. I want to get all data within a date range of today + 2 weeks (Expiring).
I have wrote:
$format = 'Y-m-j';
$date = date ( $format );
$new = date ( $format, strtotime ( '+14 day' . $date ) );
$start = date("Y-m-d", strtotime($new));
$today = date('Y-m-d');
$q = "SELECT * FROM listing WHERE dd_end BETWEEN '".$today."' AND '".$start."'";
while($row = mysql_fetch_assoc($q)){
$listing_id = $row['listing_id'];
echo "$listing_id";
}
So what I want to achieve is for the query to pull all the rows from now until 5th October. I've echo'd the variables and they show they're in the correct form (YYYY-MM-DD) to compare within the database but no results are returning.
Any help would be greatly appreciated. Many thanks in return.
Well, assuming that the mysql database has the same date that your server, you could let the mysql database do all the date calculations.
A little something like this:
SELECT *
FROM listing
WHERE dd_end BETWEEN CURDATE() AND (CURDATE() + INTERVAL 14 DAY)
On the other hand, i think Paul S's answer may fix your problem.
Edit:
You forgot to call mysql_query before the mysql_fetch_assoc() function.
$result = mysql_query($q);
while ($row = mysql_fetch_assoc($result))
{
$listing_id = $row['listing_id'];
echo "$listing_id";
}
If dd_end is a date you may want to read a certain section on the MySQL docs: http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#operator_between
For best results when using BETWEEN with date or time values, use
CAST() to explicitly convert the values to the desired data type.
Examples: If you compare a DATETIME to two DATE values, convert the
DATE values to DATETIME values. If you use a string constant such as
'2001-1-1' in a comparison to a DATE, cast the string to a DATE.
May this is the right way ?
$start = date("Y-m-d", strtotime('+14 day' . $date));
Read:
http://php.net/manual/en/function.strtotime.php
strtotime has a second argument.
$format = 'Y-m-j';
$date = date ( $format );
$new = date ( $format, strtotime ( '+14 day' . $date ) );
$start = date("Y-m-d", strtotime($new));
Should be:
$new = strtotime('+14 day', time());
$start = date("Y-m-d", $new);
$today = date('Y-m-d');
$q = mysql_query("SELECT * FROM listing WHERE dd_end BETWEEN '".$today."' AND '".$start."'");
while($row = mysql_fetch_assoc($q)){
$listing_id = $row['listing_id'];
echo "$listing_id";
}

Categories