Failing to compare php date with mysql date - php

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

Related

PHP/SQL Converting timestamp

So I am working on a simple website and I ran into a problem. I have a subscription based website and I have a date expired for when their subscription ends. This all works well, but when I tried to display the expiration date I ran into problems. The first 3 lines are what i have been trying. It seems as if the timestamp isnt correctly being transferred from the database because when I did my test at the button, this displayed the correct date. The top 3 lines always give me this: 1970/01/01
// Get Expiration Date
// Always gives me 1970/01/01
$datexpire = "SELECT date-expire FROM users WHERE username='{$_SESSION['username']}'";
$timestamp = mysqli_query($link, $datexpire);
$date = date("Y/m/d",$timestamp);
//This works
$timestamp2 = 1537847863;
$date2 = date("Y/m/d",$timestamp2);
If anyone could help that would be much appreciated
i think your code should be something like
$datexpire = "SELECT date-expire FROM users WHERE username='{$_SESSION['username']}'";
$result = mysqli_query($link, $datexpire);
$row=mysqli_fetch_assoc($result));
$timestamp = $row['date_expire'];
$date = date("Y/m/d", $timestamp);
echo $date;
please check for column name.. if it is date-expire or date_expire ??? (dash or underscore ??)
mysqli_query returns a mysqli_result object or a boolean value.
You want to fetch a row from your given object, like so:
$datexpire = "SELECT `date-expire` FROM users WHERE username='{$_SESSION['username']}'";
$result = mysqli_query($link, $datexpire);
$row = mysqli_fetch_assoc($result);
$date = date("Y/m/d", $row["date-expire"]);

php ORA-01861: literal does not match format string

I'm writing a php script to insert data into an Oracle database, and I'm getting ORA-01861: literal does not match format string when I try to run it. It has something to do with the date and they way it's calculated, but I'm not sure how/where to fix it. In the table, the log_date is type date. Below is the section of code that I'm working with for the date after I've already established the db connection. Does it need to go in my $query definition?
$ticks = $mnemonic->timestamp . "\n";
$seconds = ($ticks - 621355968000000000) / 10000000;
$day = date("Y-m-d H:i:s", $seconds);
$query = "INSERT into TLM_Item(log_date) Values('$day')";
$updt = ociparse($conn, $query);
if(!$updt){
print "No query \n";
exit;
}
$r = ociexecute($updt , OCI_COMMIT_ON_SUCCESS);
Oracles default date format is not YYYY-MM-DD. Fortunately, though, Oracle supports the keyword DATE so support dates. I haven't used it in this context, but it should work:
$query = "INSERT into TLM_Item(log_date) Values (DATE '$day')";
Alternatively, you could use the built-in function to_date():
$query = "INSERT into TLM_Item(log_date) SELECT to_date('$day', 'YYYY-MM-DD HH24:MI:SS') FROM DUAL";

How can i Compare dates in php with different formats Y/m/d and Y/m/d H:M stored in a database?

I have a query like that:
$monitor = $db->query("SELECT * FROM event, step WHERE step = idstep ");
$countquery = $monitor->rowCount();
if ($countquery == 0){
echo "no records";
}else{
echo "show records";
and i would like to be:
$today = ("Y/m/d");
$monitor = $db->query("SELECT * FROM event, step WHERE step = idstep AND datastep = $today");
$countquery = $monitor->rowCount();
if ($countquery == 0){
echo "no records";
}else{
echo "show records";
In my database, datastep is stored like: Y/m/d H:M and when i compare the 2 dates i have no results.
i would like to not consider hours and minutes.
How can i compare the dates, without changing the field datastep in the database?
I would like to convert datastep in Y/m/d format.
Use DateTime object.
$today = new DateTime("2014/07/31");
and the you can format it whatever you like:
$today->format("Y/m/d H:M");
But I think you could also use DATE() in mysql:
SELECT * FROM event, step WHERE step = idstep AND DATE(datastep) = DATE('$today');
DATE() function in mysql will return only day, in this way DATE('2014/07/31 12:00') will be equal to DATE('2014/07/31').

Unexpected (negative time) when calculating the elpased time between two dates - php and mysql

I want to get difference in seconds between the current date and certain date which is stored in a database as DATETIME type. I'm getting this date with this function:
function get_date_last_action($username)
{
$id = $this->get_username_id($username);
$query = "SELECT date_last_action".
"FROM user".
"WHERE user.id ='" . $id . "'";
$result = mysql_query($query);
$date_last_action = mysql_fetch_array($result);
return $date_last_action[0];
}
In a another code, I call this function:
$date = $h_db_functions->get_date_last_action("user1");
$currentTime = time();
$timeInPast = strtotime($date);
$differenceInSeconds = $currentTime - $timeInPast;
What's weird is that I'm getting a negative value.
If you are getting a negative answer to "now - then", then "then" is in the future.
To confirm, try echo $date.
If the difference is fairly small, then it means your database and PHP processes are not using the same timezone. Be sure to set date_default_timezone_set in PHP, and SET time_zone = ... in MySQL, to the same identifier.
Use this approach:
$timeFirst = strtotime('2014-04-15 18:20:20');
$timeSecond = strtotime('2014-04-11 18:20:20');
$differenceInSeconds = $timeSecond - $timeFirst;
Note: Be sure, that you are executing the functions with right parameters.
In your case:
$currentTime = time();
$timeInPast = strtotime($date); // date should be in YYYY-DD-MM HH:MM:SS format
$result = $currentTime - $timeInPast;
Sources:
date() function
strtotime() function
method source
Demo

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);

Categories