Check current date against date in database - php

What I'm doing with this code is checking the database for a date that ends editing(Say Today's date is 12/30/11 last date for edits was or is 12/12/10 = LOCKED or Todays date is 12/30/11 last date for edits was or is 12/12/13 = UNLOCKED & forwarded to edit site)
So with that in mind here's the problem: the code i have always says your account is locked no matter the lock date and i am at a lost for a solution :(.
By the way please keep in mind that the headers have already been sent by this point.
<?php
$id = $_GET['id'];
// Define MySQL Information.
$mysqlhost="***************"; // Host name of MySQL server.
$mysqlusername="**********"; // Username of MySQL database.
$mysqlpassword="*********"; // Password of the above MySQL username.
$mysqldatabase="*************"; // Name of database where the table resides.
// Connect to MySQL.
mysql_connect("$mysqlhost", "$mysqlusername", "$mysqlpassword")or die("Could not connect to MySQL.");
mysql_select_db("$mysqldatabase")or die("Could not connect to selected MySQL database.");
$infosql = "SELECT * FROM premiersounds_users WHERE customer_id = $id";
$inforesult = mysql_query($infosql) or die(mysql_error());
$info = mysql_fetch_array($inforesult);
$l_date=$info['lockout_date'];
//Get current date from server
$format="%m/%d/%y";
$c_date=strftime($format);
//set sessions
$_SESSION['current_date'] = $c_date;
$_SESSION['lockout_date'] = $l_date;
//Check is Current date = lockout date
if ($c_date <= $l_date) { header("location:/planner_scripts/documnet_editors /edit_weddingplanner.php?id=$id"); } else {echo 'Whoops! Were sorry your account has been locked to edits because your event is less than 48 hours from now or your event has passed. To make changes to your event please contact your DJ.'; echo'<br/>'; echo ' Todays Date: ';echo $c_date; echo ','; echo ' Last Date for edits: '; echo $l_date;}
?>
<?php
//Destroy Session for Lockout Date to prevent by passes
unset($_SESSION['lockout_date']);
?>

A couple of things ...
The code as it was posted is massively open to SQL-injection
attacks. You should always sanitize user data before including it in
a db query. I add a mysql_escape_string() call in the code below
to prevent this as well as mention a simple integer cast. There are
other ways to accomplish this. You can learn how by searching SO on
the topic.
One easy way to compare dates is to use PHP's DateTime class.
The code below creates instances of DateTime ... one for the
current date and one from the lockout date retrieved from the
database. Once you have these objects, you can compare the two.
<?php
$id = $_GET['id'];
// Define MySQL Information.
$mysqlusername=""; // Username of MySQL database.
$mysqlpassword=""; // Password of the above MySQL username.
$mysqldatabase=""; // Name of database where the table resides.
// Connect to MySQL.
mysql_connect("$mysqlhost", "$mysqlusername", "$mysqlpassword")or die("Could not connect to MySQL.");
mysql_select_db("$mysqldatabase")or die("Could not connect to selected MySQL database.");
// IMPORTANT: PREVENT SQL INJECTION
$id = mysql_escape_string($id);
// Or, if $id is supposed to be an integer just do this ...
// $id = (int) $id;
$infosql = "SELECT * FROM premiersounds_users WHERE customer_id = $id";
$inforesult = mysql_query($infosql) or die(mysql_error());
$info = mysql_fetch_array($inforesult);
//Get current date from server
$c_date = new DateTime();
$l_date = new DateTime($info['lockout_date']);
//Check is Current date = lockout date
if ($c_date->format('Y-m-d') <= $l_date->format('Y-m-d')) {
header("location:/planner_scripts/documnet_editors/edit_weddingplanner.php?id=$id");
} else {
echo 'Whoops! Were sorry your account has been locked to edits because your event is less than 48 hours from now or your event has passed. To make changes to your event please contact your DJ.';
echo'<br/>';
echo ' Todays Date: ';
echo $c_date;
echo ',';
echo ' Last Date for edits: ';
echo $l_date;
}
?>

You are comparing dates as strings. You're comparing something like 12/30/2011 to something like 12/11/2011 or whatever. PHP can and will do this, but it will treat them like strings.
The main oddity that this will make is that 0's are not implied as with numeric types.
Also, your date formats will not match. MySQL returns something like 2011-12-30, whereas your strftime will do something like 30/12/2011.
Try something like
$c_date_stamp = strtotime($c_date);
$today = strtotime('today');
if($c_date_stamp <= $today) { }
This will convert the dates to unix timestamps before comparison. Another option would be to leave them in string form, but be weary of the implications that can have.
For example, if you do it in string form, the magnitude of the date-parts will need to be in descending order:
if($c_date <= date('Y-m-d'))
Also note that if one is using a leading zero on days < 10, the other one needs to do so too.

Related

MySQL table not updating through PHP cron job at specified time

I am working on an Android App which has a MySQL database which contains a table that has all the login details of each user.In that table I have column named "Status" which is initially assigned to 0 for every user.Everyday when the user logs in to his account and submits the data(clicks the submit button) the status is changed to 1.And every night at 12 AM the status should be reset to 0.Also, if the user doesnot submit the data until 10 AM for a day, a row should be automatically inserted to the MySQL table with a column value as "No Records" for the particular user whose status is still 0.So,I have a created a PHP file which runs as a cron job in cpanel. The PHP file checks the time every hour. And the current time 12 AM and 10 AM, it should do the required changes.But I am not getting the required result with my PHP script.The script is given below:
<?php
require "connection.php";
$get_time = "select date_format(NOW(), '%H:%i A') as current_daily_date from dual;";
$convert_time = mysqli_query($connect,$get_time);
$php_time = mysqli_fetch_assoc($convert_time);
$final_time = $php_time["current_daily_date"];
$dateTime = new DateTime('now', new DateTimeZone('Asia/Kolkata'));
$d = $dateTime->format("H:i A ");
$e = $dateTime->format("d/m/y");
echo $d;
$s = '00:00';
$g = strtotime($s);
$p = date('H:i A',$g);
echo $p;
$c = '10:00';
$q = strtotime($c);
$r = date('H:i A',$q);
echo $r;
if($d == $p) {
$run = "UPDATE login SET status = 0;";
$connect->query($run);
echo "Status updated";
}
else if($d == $r) {
$second_run = "INSERT into attendance (name,date,attendance) VALUES ((SELECT name from login where status = 0 ), '$e' , 'No Records');";
$connect->query($second_run);
echo "Marked as No Records";
}
else {
echo "Not the correct time to change the status.";
}
$connect->close();
?>
I have set my email for the cron job so that I get the output to my mail. But even at 12 AM ,the table did not update.
The output was:
00:00 AM 00:00 AM10:00 AMNot the correct time to change the status.
I don't know where I am going wrong.Can anyone please check and let me know what is the issue?
The format of the INSERT SELECT is incorrect:
$second_run = "INSERT into attendance (name,date,attendance) SELECT name, ****, **** from login where status = 0";
You don't need the VALUES bit and I'm not sure what the end segment was at all. You also are trying to insert 3 values whilst only providing one, I've put ****'s in there where you need to put your other values.
You should also turn on error reporting in your script if you didn't get any errors from it as this would have been an error.
error_reporting(E_ALL);
ini_set('display_errors', 1);

PHP MYSQL > search for username and echo a columns data

I'm looking for a simple php script that will look through my database for a username and echo a column. The column I want to echo is a date.
I'm making a script that checks if the date assigned to the user is todays date.
$datenow = date("Y-m-d");
$user = $_SESSION['username'];
$connection = mysql_connect('localhost', 'username', 'password');
mysql_select_db('database name');
$result = mysql_query("SELECT accessfrom FROM users WHERE username = $user");
// Now I need a simple way to check if the results date = $datenow(from above)
mysql_close(); //Make sure to close out the database connection
Don't use MySQL. It is deprecated. So, use mysqli_.
Presumably, username is a string. So, you have a mismatch in your comparisons. The naive solution is to add single quotes:
$result = mysql_query("SELECT accessfrom FROM users WHERE username = '$user'");
The correct solution is to use mysqli_ and use parameters for passing in values. This not only solves your problem. It also prevents SQL injection attacks, and teaches you how to correctly write queries.
First you should use pdo or something.
foreach($result as $v){
if ($v['date'] === $datenow){
//your have a hit
}
}
but you should do it in your query (where date = $datenow) or something

Telegram bot can't receive data from table with mysqli

I'm creating bot for Telegram.
And everything was OK, until I started to connect my bot with my database.
So, I've created table with fields "date","day","schedule".
And I want to make my bot to get a schedule by data from table.
But it can't. And I don't know why.
Here is a part of my code which belongs to DB connection.
<?php
//Connect to db with my params
$db = new mysqli('###', '###', '###', '###');
//Receive today's date
$date = date('Y-m-d');
/*
* Schedule - is what I'm looking for(some text in the table), knu - table's name
* date - table's field with date(format YYYY-MM-DD)
*/
$query = "SELECT schedule FROM knu WHERE `date` = '$date'";
$res = $db->query($query);
$row = $res->fetch_assoc();
//Send message to user
if($message == "a")
{
$date = date('Y-m-d');
$answer = $row;
sendMessage($chatId, $answer);
}
And this code doesn't work. I've tried a lot of times with different ways but still no answer with my bot.
What's wrong with my code and how to make it work?
$row isn't a string, it's an array. You probably want $answer['schedule'] or even just $row['schedule'] allowing you to remove the line $answer = $row;.

Error in script sending automatic birthday wish to a registered user in php

I have written the script of sending automatic e-mail for a given date. I have already set up the cron job to execute this once a day for a given time. But it is not working. Can anyone show me the error here. I'm really new to this.
What I'm really supposed to do is to send an automatic email to a user on their birthday
<?php
$host="mysql117.000webhost.com/";//hostname
$username="abc";//mysql_username
$password="123";//mysql_password
$dbname="abc";//Database name
$tbl_name="customer_info";//table name
$date = date("2005-09-23"); //here my date format in my DB is 2010-09-30
$link = mysqli_connect('$host','$username','$password','$dbname');
if($link && mysqli_select_db('$dbname', $link))
{
$grabBday = "SELECT b_day,DATE_FORMAT(b_day,'2015-%m-%d') FROM customer_info where b_day = '2002-09-24'";
//here it will take the name of the person whose bday is on a particular date,I just hard coded this date to check if this is working
if($rs = mysqli_query($link, $grabBday))
{
while(mysqli_fetch_array($rs))
{
mail('abc92#yahoo.com', 'HAPPY BIRTHDAY', 'Many Happy Returns of the day');
}
}
} ?>
I am seeing logical difference as you are searching where b_day=$date where $date='2015-09-23' but dob can be '2002-09-23' or '1997-09-23' etc. so you will not get desired output, so you can change your query as per below if everything other than it is fine.
SELECT * FROM
tbl_name
WHERE CONCAT(YEAR(CURDATE()),DATE_FORMAT(b_day,'-%m-%d')) = $date

Redirecting page after headers are set with php

Ok so im at a loss. I can not figure out how to redirect someone once the headers are sent. The purpose of this script is if the date is valid they get redirected to the edit page. If the date is not valid it stops them and tells them why they are not able to edit.
<?php
$id = $_GET['id'];
// Define MySQL Information.
$mysqlhost="************************"; // Host name of MySQL server.
$mysqlusername="**************"; // Username of MySQL database.
$mysqlpassword="**************"; // Password of the above MySQL username.
$mysqldatabase="**************"; // Name of database where the table resides.
// Connect to MySQL.
mysql_connect("$mysqlhost", "$mysqlusername", "$mysqlpassword")or die("Could not connect to MySQL.");
mysql_select_db("$mysqldatabase")or die("Could not connect to selected MySQL database.");
$infosql = "SELECT * FROM premiersounds_users WHERE customer_id = $id";
$inforesult = mysql_query($infosql) or die(mysql_error());
$info = mysql_fetch_array($inforesult);
$l_date=$info['lockout_date'];
//Get current date from server
$format="%m/%d/%y";
$c_date=strftime($format);
//set sessions
$_SESSION['current_date'] = $c_date;
$_SESSION['lockout_date'] = $l_date;
//Check is Current date = lockout date
if ($c_date >= $l_date)
{ header("location:/planner_scripts/documnet_editors/edit_weddingplanner.php?id=$id"); } else {echo 'Whoops! Were sorry your account has been locked to edits because your event is less than 48 hours from now or your event has passed. To make changes to your event please contact your DJ.'; echo'<br/>'; echo ' Todays Date: ';echo $c_date; echo ','; echo ' Last Date for edits: '; echo $l_date;}
?>
I would make sure this is the first code run so that no headers have been sent yet, but if you cannot put it there, you have 2 choices:
Use javascript: window.location.url = ...
Put a meta refresh tag in the <head> section of your page: <meta http-equiv="refresh" content="0;url=...">
2 choices assuming you cannot change the code before your section is run...
You could use output buffering to stop anything being rendered. Alternatively just make sure the redirect is done in logic before echoing anything to the user.
Correct syntax is Location: http://....
Note:
Capital L
A space between : and the URL
An absolute URL (relative URLs aren't RFC compliant though might work in most browsers)

Categories