I have an Android app which is used to store data of users in MySQL database using PHP. I need to do some validations according to the date.The MySQL Database has a predefined date for each user.The date increases by 1 day whenever a user inserts data twice for that day.And when the date exceeds the current date,it shows a message that "the user has already submitted data for the day".
My PHP file is :
<?php
require "conn.php";
$user_mobile = $_POST["mobile_num"];
$user_pass = $_POST["password"];
$mysql_qry = "select * from employee_data where mobile like '$user_mobile' and password like '$user_pass';";
$result = mysqli_query($conn,$mysql_qry);
if(mysqli_num_rows($result) > 0 ) {
$row = mysqli_fetch_assoc($result);
$name= $row["name"];
$_POST['user'] = $name;
$last_updated = $row["last_updated_date"];
$_POST['user'] = $name;
$_POST['date'] = $last_updated;
echo "Login successful. Welcome_" .$name;
echo "_Date:" .$last_updated;
$now = new DateTime("Asia/Kolkata");
$n = ($now->format('Y-m-d'));
if(($last_updated > $n)) {
echo "exceeded";
}
?>
But what is happening is if "$last_updated"(the date which is changing everytime) is the current date,then it is not going inside the if condition. So if "$last_updated" is today's date, then the user gets the message "the user has already submitted data for the day". I tried doing an echo of "$n" and it gives the current date. So, it should not go to the if-condition because ($last_updated == $n) . But its going inside the if-condition when ($last_updated == $n).I don't know why this is happening.Can anyone please help me with this?
Try to change your
$now = new DateTime("Asia/Kolkata");
to:
$now = new DateTime(null, new DateTimeZone('Asia/Kolkata'));
You need to compare them as objects.. Try something like this..
$now = new DateTime("Asia/Kolkata");
if (new DateTime($last_updated) > $now) {
echo "exceeded";
}
I'm not sure if your timezones are set properly on your server but to be sure you could do one of the following as well..
$now = new DateTime('Asia/Kolkata');
if (new DateTime($last_updated, new DateTimeZone('Asia/Kolkata')) > $now) {
echo "exceeded";
}
Or probably even better..
date_default_timezone_set('Asia/Kolkata');
$now = new DateTime('now');
if (new DateTime($last_updated) > $now) {
echo "exceeded";
}
Your issue is that since you are not keeping the time in the database and when you compare the date with now which includes the time, the now will always be greater than the date you pull from the database.
The database time 2017-03-17 becomes 2017-03-17 00:00:00 php time.
When you generate php now time it will be 2017-03-17 xx:xx:xx which will always be greater than database time
$last_updated = new DateTime($row["last_updated_date"],new DateTimeZone("Asia/Kolkata"));
$today = new DateTime('now',new DateTimeZone("Asia/Kolkata")); //gets current date time
$today->setTime(0,0); // back to the beginning of the day
//echo $last_updated->getTimestamp . | . $today->getTimestamp; // for debugging purpose
if(($last_updated->getTimestamp >= $today->getTimestamp)) {
// note that I have used '>=' to allow the current date
}
You can also use the DateTime->diff() function.
Reference: http://php.net/manual/en/class.datetime.php
Related
I am trying to prevent spam in my contact form. When anyone contact using contact form, I am saving his IP Address in Database with Current Time. If someone try contact, I am checking IP in database and if there IP address entry in Database, I am getting timestamp of it and comparing it with current timestamp but I think there something wrong with it and its giving me wrong time and so user are still able to send messages.
I have defined TimeZone like below
define('TIMEZONE', 'Asia/Kolkata');
date_default_timezone_set(TIMEZONE);
$date = date('Y/m/d h:i:s', time());
I am inserting write time in database same as echo in php.
Now I am getting and comparing both time like below
$last_time = $row['time'];
$current_time = $date;
if(($current_time-strtotime($last_time )) > 1800) {
//send mail
}
else {
// give error
}
I have tried echo both time and I am getting result like this
$last_time = 2018-09-23 07:56:37
$current_time = 2018/09/23 07:56:51
($current_time-strtotime($last_time ) = -1537667579
I don't know whats wrong with it.
Let me know if there anything wrong with it.
Also convert the current time into strtotime. Make sure both date format should be same
define('TIMEZONE', 'Asia/Kolkata');
date_default_timezone_set(TIMEZONE);
$date = date('Y/m/d h:i:s', time());
$last_time = $row['time'];
$current_time = $date;
if((strtotime($current_time)-strtotime($last_time )) > 1800) {
//send mail
}
else {
// give error
}
$fetch=mysql_query("select * from code where user_email='$email' order by reg_date desc limit 1");
$db=mysql_fetch_array($fetch);
print_r($db);
$db_date=$db['reg_date'];
$db_time=$db['time'];
echo "DB_Date:".$db_date."--";
echo "DB_time:".$db_time."--";
$current_date = date('Y-m-d');
echo "present date".$current_date."--";
$curent_time = date('H:i:s');
echo "current time:".$curent_time."--";
$first_time = strtotime($curent_time);
$last_time = strtotime($db_time);
$time = $first_time - $last_time;
$time_differenc= ($time/60)%60;
echo "difference".$time_difference."--";
In the above code, i'm getting the present time,date and time,date value stored in the db correctly,but when i tried to find the difference between current time and time stored in the database, i cant get the difference.
When i give the time directly like strtotime('11:30:02'); the difference can be calculated but when i tried to get the time value which is stored in database, i cant!!!
Help me soon!!! I'm trying a lot....
Try this you need to specifically set the timezone else by default it takes UTC
$dbdatetime = $row['datetime'];//datetime from database: "2014-05-18 18:10:18"
date_default_timezone_set("Asia/Kolkata"); //setting default timezone based on your location
$curdatetime = date("Y-m-d H:i:s"); //current datetime
if($curdatetime > $dbdatetime){
$diff = abs(strtotime($curdatetime) - strtotime($dbdatetime));
}else{
$diff = abs(strtotime($dbdatetime) - strtotime($curdatetime));
}
echo "The difference is "$diff/60." minutes";
I'm making a news website for games and I want a page where you can find all the news subject. So I decided to use it like a lot of webpages do.
Example:
Now I want it like that, but i don't know how to make that like that. I've made a little beginning and I hope you guys can help me with this!
$query = mysql_query("SELECT * FROM `gb_news` order by `datetime` DESC");
while($news = mysql_fetch_array($query)) {
echo $news['title'];
echo $news['datetime'];
}
It's a really simple code, but I only want to know how I add these days when an artical has a new date in the database.
Store the date outside your loop, then display a title only when the date changes.
$date = "";
while ($news = mysql_fetch_array($query)) {
if ($news['datetime'] != $date) {
$date = $news['datetime'];
echo $date;
}
echo $news['title'];
}
Something like this may work for you:
$query = mysql_query("SELECT * FROM `gb_news` order by `datetime` DESC");
$prevDate ='';
while($news = mysql_fetch_array($query))
{
$tmpDate = DateTime::createFromFormat('Y-m-d H:i:s', $news['datetime']);
if($prevDate!=$tmpDate)
{
$prevDate = $tmpDate->format('d/m/Y');
echo '<h1>'.$prevDate.'</h1><hr />';
}
echo '<p>'.$tmpDate->format('H:i').' - '.$news['title'].'</p>';
}
This is assuming your datetime column is in the format YYYY-MM-DD hh:mm:ss and you want to display the date as DD/MM/YYYY, obviously edit to taste!
Also your PHP version must be >= 5.3.0 to use the DateTime class
Well what you can do is store the date and then change the layout each time the date changes:
while($news = mysql_fetch_array($query)) {
if(empty($date) || $date != date("format", $news['datetime'])){
$date = date("format", $news['datetime']);
//echo/print some html to show new section
}
echo $news['title'];
echo $news['datetime'];
}
This will handle the date comparisons and knowing when to change dates. "format" indicates the kind of date formatting you would like since you can echo/print the $date.
PHP date
NOTICE: Do not use MySQL_* for it has been deprecated as of PHP 5.5. Use MySQLi_* or PDO instead
I'm not sure I quite understand what you're trying to accomplish. To get your data to display like the image you included you would want to group items of the same date either in MySQL or PHP (or combination really).
Something like:
while ($news...) {
// Get this article date
$thisDate = new DateTime($news['datetime']) // Assuming this is a true datetime value
// Compare this article date with previous article date to determine if we should start a new date header
if (!empty($onDate) // We have previous articles to compare with
&& ($thisDate->format('l d F') == $onDate)) // This article date matches previous so keep in same group
{
echo $news['title'];
} else { // No existing articles or new date = new header
$onDate = $thisDate->format('l d F'); // See options: http://www.php.net/manual/en/function.date.php
echo $onDate
echo $news['title'];
}
}
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
I am using the following code to attempt to compare the current date with a date entry in a mySql database. It's code that I have found online and adapted as all the examples I have found hard-code the date to compare the current date with.
The trouble is even dates in the future are being marked as expired and I can't understand why this would be.
I am afraid that I am still new to PHP, so I may be making a schoolboy error!
$exp_date = KT_formatDate($row_issue_whatson1['dateToShow']);
$todays_date = date("d-m-Y");
$today = strtotime($todays_date);
$expiration_date = strtotime($exp_date);
if ($expiration_date > $today) { echo "Not expired"; } else { echo "expired"; }
Any help would be most appreciated.
I should add that the date time format used in the database entries is dd/mm/yyyy
Instead of making a string then converting it to a timestamp, simply use mktime:
<?php
$today = mktime(
0, // hour
0, // minute
0 // seconds
);
?>
The rest of the values will be filled according to today's date. If this still gives problems, put in some echo's for the values of $exp_date and $expiration_date.
Edit
Since this solved the problem, the discrepancy you were seeing was because you were doing the opposite with date('d-m-Y'). You were asking for the current date and the time values are then filled in with the current time. The expiration date in the database is likely set at midnight. With both dates being equal, and it being say 11am now, you are comparing if (00:00:00 > 11:00:00) which fails.
$exp_date = 14/05/2011 // todays date, int
$server_date = server.date() // servers date, int
// check exp_date against server date
if ( $server > $exp_date)
{ echo "Sorry your 'service' has expired"; }
else
{ echo "Welcome 'members_name' to StackOverflow"; }
Try that. However you need the right date format, as server.date() is probably different in PHP.
If problem still persists I would check whether your dates are strings or integers or both. That could possibly be the issue.
Hope that helps.
DL.
Your function does not seem to be valid.
function KT_formatDate( $exp_date){
$exp_date = strtotime($exp_date);
$now = time();
if ($now > $exp_date)
return 'expired';
else
return ' Not expired';
}
$response = KT_formatDate($row_issue_whatson1['dateToShow']);