compare if date from database is bigger than current date - php

I'm stuck on this one.
It sounds quite easy what I'm trying to accomplish, still I can't get it to work...
I have several user stored in a database. They can visit a page after login. But each user has an end date. So if this day has passed, he won't be able to see the page anymore and will be redirected to another page. But there is a different date for each user.
When an user enter his credentials, a $_SESSION is created that stores his login name. I need the sql to get the date from the specific user using this $_SESSION value.
What I have so far:
$sql="SELECT * FROM $tbl_name WHERE licentiehouder=$naamLicentiehouder";
$naamLicentiehouder = $_SESSION['doorsturen'];
$result=mysql_query($sql);
$row = mysql_fetch_row($result);
$mydate = $row['vervaldatum'];
$curdate=strtotime("now");
if($curdate <= $mydate && $_SESSION['doorsturen'] == 'userONE') {
header("Location: userONE.php");
} else if ($curdate <= $mydate && $_SESSION['doorsturen'] == 'userTWO') {
header("Location: userTWO.php");
} else if($curdate > $mydate) {
header("Location: extend_license.php");
}
So again, every user has it's own license, which will expire on an exact date. This date is stored in the database. So if userONE's logging in, $_SESSION value is set to userONE. sql reads this values and gets only the row that's matching this value. If today (current date) is bigger than the date stored (so his license is expired), he will be redirected to a page to extend his license. If not, he will be able to see his personal page.
Hope anyone can help?!

Your variable $naamLicentiehouder is undefined at the time you run your query. Try:
$naamLicentiehouder = $_SESSION['doorsturen'];
$sql="SELECT * FROM $tbl_name WHERE licentiehouder='$naamLicentiehouder'";
Also mysql_query(), and the like, are depreciated. Use mysqli. I prefer the Object Oriented approach, since it saves a lot of repetitive typing.
To clarify, the Object Oriented approach, on a separate restricted page we'll call connect.php:
<?php
// reusable db() function can be called inside other functions
function db(){
return new mysqli('host', 'username', 'password', 'database');
}
?>
Now on your other page:
<?php
include_once 'restricted/connect.php'; $db = db();
if($db->connect_error)die("Connection Failure: {$db->connect_error}");
$naamLicentiehouder = $_SESSION['doorsturen']; // I would shorted this variable
if($result = $db->query("SELECT vervaldatum FROM your_table_name WHERE licentiehouder='$naamLicentiehouder'")){
if($result->num_rows > 0){
$row = $result->fetch_object(); $mydate = $row->vervaldatum;
$curdate = strtotime('now');
if($curdate <= $mydate && $naamLicentiehouder === 'userONE'){
header('LOCATION: userONE.php'); die;
}
elseif($curdate <= $mydate && $naamLicentiehouder === 'userTWO'){
header('LOCATION: userTWO.php'); die;
}
elseif($curdate > $mydate){
header('LOCATION: extend_license.php'); die;
}
else{
die('Date Issue.');
}
}
else{
die('No results were found.');
}
}
else{
die('Error :'.$db->error);
}
$result->free(); $db->close();

You seem to be getting a timestamp with $curdate=strtotime("now"); What you are getting from the database is likely (although I can't be sure) a date, not a timestamp. Use strtotime on it too:
$mydate = strtotime($row['vervaldatum']);
That should do it.

Related

PHP SQL query doesnt return a result

I have a button in a webapp that allows users to request a specially formatted number. When a user click this button 2 scripts run. The first that is fully functional, looks at a number table finds the largest number and increments it by 1. (This is not the Primary Key) the second script which is partially working gets the current date and runs a SQL query to get which period that date falls in. (Periods in this case not always equaling a full month) I know this script is at least partially working because I can access the $datetoday variable called in that script file. However it is not returning the requested data from the periods table. Anyone that could help me identify what I am doing wrong?
<?php
include 'dbh.inc.php';
$datetoday = date("Ymd");
$sql = "SELECT p_num FROM periods where '$datetoday' BETWEEN p_start AND p_end";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../quote.php?quotes=failed_to_write");
exit();
} else {
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_assoc($result);
$pnum = $row;
mysqli_stmt_close($stmt);
}
If it helps any one I published my code to https://github.com/cwilson-vts/Quote-Appliction
So first off, I do not use msqli and never learned it. However, I believe I get the gist of what you want to do. I use PDO because I FEEL that it is easier to use, easier to read and it's also what I learned starting off. It's kinda like Apple vs. Samsung... no one product is exactly wrong or right. And each have their advantages and disadvantages. What I'm about to provide you will be in PDO form so I hope that you will be able to use this. And if you can't then no worries.
I want to first address one major thing that I saw and that is you interlacing variables directly into a mysql statement. This is not considered standard practice and is not safe due to sql injections. For reference, I would like you to read these sites:
http://php.net/manual/en/security.database.sql-injection.php
http://php.net/manual/en/pdo.prepared-statements.php
Next, I'm noticing you're using datetime as a variable name. I advise against this as this is reserved in most programming languages and can be tricky. So instead, I am going to change it something that won't be sensitive to it such as $now = "hello world data";
Also I'm not seeing where you would print the result? Or did you just not include that?
Another thing to consider: is your datetime variable the same format as what you are storing in your db? Because if not, you will return 0 results every time. Also make sure it is the right time zone too. Because that will really screw with you. And I will show you that in the code below too.
So now on to the actual code! I will be providing you with everything from the db connection code to the sql execution.
DB CONNECTION FILE:
<?php
$host = '127.0.0.1';
$user = 'root';
$pw = '';
$db = 'test'; // your db name here (replace 'test' with whatever your db name is)
try {
// this is the variable will call on later in the main file
$conn = new PDO("mysql:host=$host;dbname=$db;", $user, $pw);
} catch (PDOException $e) {
// kills the page and returns mysql error
die("Connection failed: " . $e->getMessage());
}
?>
The data file:
<?php
// calls on the db connection file
require 'dbconfig.php';
// set default date (can be whatever you need compared to your web server's timezone). For this example we will assume the web server is operating on EST.
date_default_timezone('US/Eastern');
$now = date("Ymd");
// check that the $now var is set
if(isset($now)) {
$query = $conn->prepare("SELECT p_num FROM periods WHERE p_start BETWEEN p_start AND :now AND p_end BETWEEN p_end AND :now");
$query->bindValue(':now', $now);
if($query->execute()) {
$data = $query->fetchAll(PDO::FETCH_ASSOC);
print_r($data); // checking that data is successfully being retrieved (only a troubleshooting method...you would remove this once you confirm it works)
} else {
// redirect as needed and print a user message
die("Something went wrong!");
}
$query->closeCursor();
}
?>
Another thing I want to mention is that make sure you follow due process with troubleshooting. If it's not working and I'm not getting any errors, I usually start at the querying level first. I check to make sure my query is executing properly. To do that, I go into my db and execute it manually. If that's working, then I want to check that I am actually receiving a value to the variable I'm declaring. As you can see, I check to make sure the $now variable is set. If it's not, that block of code won't even run. PHP can be rather tricky and finicky about this so make sure you check that. If you aren't sure what the variable is being set too, echo or print it with simply doing echo $now
If you have further questions please let me know. I hope this helps you!
I think I know what I was doing wrong, somebody with more PHP smarts than me will have to say for sure. In my above code I was using mysqli_stmt_store_result I believe that was clearing my variable before I intended. I changed that and reworked my query to be more simple.
<?php
include 'dbh.inc.php';
$datetoday = date("Ymd");
$sql = "SELECT p_num FROM periods WHERE p_start <= $datetoday order by p_num desc limit 1";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../quote.php?quotes=failed_to_write");
exit();
} else {
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while( $row = mysqli_fetch_assoc($result)) {
$pnum = $row['p_num'];
echo $pnum;
}
mysqli_stmt_close($stmt);
}
Thanks to #rhuntington and #nick for trying to help. Sorry I am such an idiot.

How can i check if a single mysql field is empty in php

After getting the user-info from my sql database I would like to check if some of the fields are empty and continue the script based on that. A simplified piece of code would look like this:
$userData = mysql_query("SELECT * FROM user WHERE user='".$user."' LIMIT 1");
if(mysql_num_rows($data) == 1){
$u_info = mysql_fetch_assoc($data);
if(empty($u_info['u_mobile'])){
echo 2;
exit();
} else {
echo 1;
exit();
}
} else {
echo 3;
exit();
}
The problem is the empty statement checking the recieved field. I've tried using empty(), isset(), not_null() and array_key_exists() with no luck and can't get around to what I'm doing wrong.
I also tried if($u_info['u_mobile']) == '' || $u_info['u_mobile']) == NULL) but that doesnæt work either.
Why is this, or how can I go about getting this information?
I need to collect the user-information and send them to fill out the information I don't have...
You're setting the query result to $userData but then you're using mysql_fetch_assoc($data); -- doh. You need to pass the variable that you set the query result to:
$u_info = mysql_fetch_assoc($userData);
It's OK, it is still 10AM EST so this can happen in the morning =)
I suggest that you turn on PHP error reporting. PHP would have alerted you that the array values were trying to access do not exist, saving you a lot of wasted frustration.
$userData = mysql_query("SELECT * FROM user WHERE user='".$user."' LIMIT 1");
if(mysql_num_rows($userData ) == 1){
$u_info = mysql_fetch_assoc($userData );
if(empty($u_info['u_mobile'])){
echo 2;
exit();
} else {
echo 1;
exit();
}
} else {
echo 3;
exit();
}
Please Run code..I think it will be compile better it was minor mistake

If statement is not working correctly

This is my first topic so far in this great webpage
The problem is this:
I'm scripting an UCP (PHP & MySQL based). I want it to show the user's status like score, money, etc. (Yeah, it's for a game) but when I click on the login button nothing happens it just erases the content of the requested fields.
It was working properly before I made some changes (Checking if the username exists)
Here's the code:
if (isset($_POST['login']))
{
$hashedpass = hash('whirlpool', $password);
$query = "SELECT * FROM users WHERE Username = '$playername' AND Password = '$hashedpass'";
$result = mysql_query($query);
$num = mysql_num_rows($result);
mysql_close();
if($num != 0)
{
echo"Account doesn't exist!";
header("Location: ucp.html");
}
else
{
$name=mysql_result($result,$i,"UserName");
$money=mysql_result($result,$i,"Money");
$score=mysql_result($result,$i,"Score");
$wantedlevel=mysql_result($result,$i,"WantedLevel");
$adminlevel=mysql_result($result,$i,"AdminLevel");
echo "<b>$name</b><br>Money: $money<br>Score: $score<br>Wanted Level: $wantedlevel<br>Admin Level: $adminlevel<br><br>";
}
}
else if (isset($_POST['register']))
{
header("Location: register.html");
}
else
{
header("Location: index.html");
}
if($num != 0)
change to:
if($num == 0)
This simply won't work here nor does it make much logical sense:
$num = mysql_num_rows($result);
mysql_close();
if($num != 0)
{
echo"Account doesn't exist!";
header("Location: ucp.html");
}
First the logic is wrong, if $num is NOT equal to 0 then your query MUST have found at least one account. So you need to change your if statement to:
if($num == 0){ //if 0 rows were found - the account was not found thus it doesn't exist
echo "Account doesn't exist!";
}
Notice also i did not add header("location: ucp.html");. You cannot display output + relocate the user to another page. You either do one or the other, or you will get an error/warning.
Finally check your MYSQL is not causing an error by adding a check at the end with :
$result = mysql_query($query) or die(mysql_error());
Final tip, you should avoid using mysql_* and look into mysqli_* or PDO best explained here:
Why shouldn't I use mysql_* functions in PHP?

My Login PHP script is malfunctioning

So I am having problems with my login script. I have a salted MD5 hash stored in my database, and well... When I use this statement followed by this code, it logs in whatever the password is.
I'm not sure if it's the syntax, or it's just the way I use it, but it logs in if the user exists even if the password is 'lalala' and the person types in 'chicken'.
$sql = ("select * from website where `Email`='$user' and `Password`='$pass'");
$query = mysql_query($sql);
if ($query) {
$data = mysql_fetch_array($query, MYSQL_ASSOC);
if (sizeof($data) > 0) {
$_SESSION['vuser'] = $_POST['vuser'];
header('Location: /');
die;
}
}
This is how it is run:
index.php --> Presses login (Sends POST data) --> login.php (This script) --> (If it logs in, it returns to /index.php, but if not, it will go to /login.php.
I have a test account on there called 'blah' with the salted MD5 hashed as 'lolcatz'. If I were to type in 'blah' in the username part, with the password as 'stackoverflow', it will go to 'index.php'
Any ideas?
try to print_r($data) to see what the mysql_fetch_array function returns. It could be that it returns FALSE, which will overpass your condition if (sizeof($data) > 0)
Your logic is incorrect. mysql_fetch_array() will return an array representing one SINGLE row of data from the query results, or a boolean FALSE in case of failure (query has no rows, or you're fetching from something OTHER than a query result).
You should be doing:
$result = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($result) > 0) {
... user exists ...
} else {
... user does not exist ...
}
Don't use this:
if ($query) {
$data = mysql_fetch_array($query, MYSQL_ASSOC);
if (sizeof($data) > 0) {
$_SESSION['vuser'] = $_POST['vuser'];
header('Location: /');
die;
}
}
What is the reason behind measuring the size of data? That is a poor way to validate.
Do this instead :
if ($query) {
if(mysql_num_rows($query)>0){
// In the above line, we check a user with that username and password exists
$_SESSION['vuser'] == $_POST['vuser'];
header('Location: /');
} else echo "Bad password";
} else echo "Connection error";
As a side note, please stop using mysql_* functions now or real soon. They are going to be removed in the next version of PHP, and are less secure. You can use the PHP PDO Class.
I am also assuming you are not storing the $username and $pass directly in the database. If you are, stop it now, and use hash functions to store the password. You can use md5 and/or sha1 hash methods.
As it is said, you can also use mysqli similar down below
$dbq=("SELECT * FROM users where username='$uname'");
$dbresult=mysqli_query($con,$dbq);
where $con is the connection query which you've to write in mysqli.
Now you can fetch the data similar down below.
$obj=$dbresult->fetch_object();
$dbmail=$obj->Email;
$dbuname=$obj->Password;
$sql = ("select * from website where `Email`='$user' and `Password`='$pass'");
$query = mysql_query($sql);
$row = mysql_fetch_array($query, MYSQL_ASSOC);
if ($row) {
$_SESSION['vuser'] = $_POST['vuser'];
header('Location:"go where ever you want to i dont care"');
}
else{ //some error message}

Check current date against date in database

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.

Categories