Compare My DB data against specific date - php

My database data are table of dates. I want to create a list to report entries of expired dates.
for that, I used the following php script:
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Batch#, Date1, Date2 FROM users";
$result = $conn->query($sql);
$now= strtotime("-1 Months");
if ($result->num_rows > 0) {
$Date1= $row["Date1"];
$Date2= $row["Date2"];
echo "<table id='t1'><tr><th>Alert</th><th>Action</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
if($Date1 >= $now)
echo "<tr><td>One month or less to expiry date of product with batch# " . $row["Batch#"]. "</td><td>Please take an action</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
I kept getting an error: "Notice: Trying to get property of non-object in C:\xampp\htdocs\Testing\AlertTest.php on line 17
0 results"
I couldn't figure out what that means or how to fix it. I've been this method before and this is the first time I get such an error.

As you are comparing the dates, you have to mind that the both dates are in same format (Date string or time stamp). For comparison both the format as timestamp is best. So using the PHP function timestamp() just convert your database time to a unique number.
Your comparison:
if($Date1 >= $now){
....
}
Here The $Date1 is a string like '2016-07-07' and the $now something like '1468057029', so the condition not goes correct / success. What you have to do is just convert both time into timestamp and execute the comparison.
$Date1 = strtotime($row["Date1"]);
$Date2 = strtotime($row["Date2"]);
Hope this helped you.

Related

Current time from SQL Server to PHP for compare

Need get info, is EndDate expired or not (EndDate is row, where typed info about date of buyed user premium)
connectuser2db();
$bile_sql = "SELECT EndDate FROM tbl_rfuser WHERE Serial = '" . $userdata['serial'] . "'";
if (!($bile_result = mssql_query($bile_sql))) {
echo "Unable to select query the Billing table";
exit;
}
$bilel = mssql_fetch_array($bile_result);
$userdata['Enddate'] = $bilel['EndDate'];
$t_logd = $bilel['EndDate'];
echo $t_logd;
result like Jul 14 2020 02:36:00:000PM (if EndDate in smalldatetime data type)
$time = date("Y-m-d H:i:s");
echo $time;
result like 2020-07-15 14:51:21
If i use $time in this row, it update enddate to curent time:
$t_login = $userdata["lastlogintime"]; // last user login in game (from mssql) Jul 15 2020 02:36:00:000PM
$t_logd = $bilel['EndDate']; // Premium EndDate (from mssql) Jul 14 2020 02:36:00:000PM
$time = date("Y-m-d H:i:s"); // current time (from php) like 2020-07-15 14:51:21
if( $t_logd <= $t_login )
{ connectuser2db();
$user_update = "UPDATE tbl_rfuser SET EndDate='" . $time . "' WHERE Serial= '" . $userdata["serial"] . "'";
mssql_query($user_update); }
It succesfully compare "lastlogin" and "enddate", and if account is new or user be online last time before EndDate expired - change EndDate to current time, that succesfully takes from $time.
But if user login after EndDate, it not works
Want this compare:
if( $t_logd <= $t_login ) //working now
Change to compare like:
if( $t_logd <= $time ) // not working now
Help please
How can I take current time from mssql or change $time for something, that can compare?
Tried strtotime, but can't do it (sql server check it in miliseconds, but my php old and can't use date("Y-m-d H:i:s:v") format)
Note, that the MSSQL PHP extension is not available anymore on Windows with PHP 5.3 and removed in PHP 7.0.0, but if you want a solution, you may try the following:
Specify how the datetime values are returned from the SQL Server by setting the mssql.datetimeconvert option in your php.ini file to Off. When this option is On the datetime values are returned converted to SQL server settings. When this option is Off the datetime values are returned in YYYY-MM-DD hh:mm:ss format.
Use date_create() to create and compare the dates as PHP datetime objects.
The next simplified example demonstrates this approach (tested with PHP 5.2.9):
<?php
// Connection
$server = 'server,port';
$username = 'username';
$password = 'password';
$database = 'database';
$conn = mssql_connect($server, $username, $password);
if (!$conn) {
echo "Error (sqlsrv_connect): ".mssql_get_last_message();
exit;
}
mssql_select_db($database, $conn);
// Statement
$sql = "SELECT DATEADD(day, -1, GETDATE()) AS [DateTime]";
$stmt = mssql_query($sql, $conn);
if (!$stmt) {
echo "Error (sqlsrv_query): ".mssql_get_last_message();
exit;
}
// Results
while ($row = mssql_fetch_assoc($stmt)) {
$datetime1 = date_create($row['DateTime']);
}
$datetime2 = date_create();
// Compare dates
echo ($datetime1 <= $datetime2) ? 'Result: <=' : 'Result: >';
// End
mssql_free_result($stmt);
mssql_close($conn);
?>
Just use GETDATE:
UPDATE tbl_rfuser SET EndDate=GETDATE() WHERE Serial= ...

Recommendation script not working when trying to combine both components

Context
I am building a simple recommendation script that serves to provide a user with the next upcoming date for a particular day of the week that he/she has booked the most.
(i.e. JohnDoe's most popular day to book is a Thursday, and the date of the next Thursday to come up is 2019/03/07)
This is what I am dealing with :
<?php
$date = new DateTime();
$date->modify('next thursday');
echo $date->format('Y-m-d');
?>
<?php require "snippets/get_booking_recommended_day.php" ?>
The first PHP code returns the next upcoming date for whatever day is asked. It works as it should. The PHP require references code from another folder that returns the users most popular day, in String format. (eg Monday, Tuesday). It also works.
My issue comes when trying to get the first bit of code to understand what is being returned from the 2nd bit of code.
I've attempted the following...
<?php
$date = new DateTime();
$date->modify('next' require "snippets/get_booking_recommended_day.php");
echo $date->format('Y-m-d');
?>
I've tried every variation possible. Nothing seems to work.
I'm quite new to PHP, and im 90% sure my coding practice is terrible but I am trying my best to grasp it - but so far this simple issue is beyond me.
Please help.
APPENDICES
Filename: snippets/get_booking_recommended_day.php
(Return the most booked day of the last 3 months by the user currently in session)
<?php
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
// Asks the qry: Of the last 90 days, what is the most booked day of the week for the current member in session?
// Min date is CURRENT_DATE() -100 instead of CURRENT_DATE() -30, because the MySQL function CURRENT_DATE() prints the date in an int format (YYYYMMDD) with no date formatting. Thus, to get the date a month ago, we must subtract this int by 100 so as to remove 1 from the 6th number in the series of numbers. Which is the 2nd M number.
$sql = "SELECT DATE_FORMAT(tbl_booking.booking_date, '%W'), COUNT(DATE_FORMAT(tbl_booking.booking_date, '%W')) AS mostpopularday
FROM tbl_booking
WHERE tbl_booking.member_ID=$_SESSION[member_ID]
AND tbl_booking.booking_date <= CURRENT_DATE()
AND tbl_booking.booking_date >= CURRENT_DATE() -300
GROUP BY DATE_FORMAT(tbl_booking.booking_date, '%W')
ORDER BY mostpopularday DESC
LIMIT 1";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["DATE_FORMAT(tbl_booking.booking_date, '%W')"];
}
} else {
// Return Nothing.
}
?>
Filename : pagebooking.php
(This is the datepicker that is located inside my pagebooking.php, its purpose is to choose the day of a booking. My hope is to populate this field with the recommended date that will be generated from the 2 PHP scripts above.).
<input name="new_booking_date" width="276" placeholder="Date" class="form-control input-md" type="date" max="<?php echo date("Y-m-d", strtotime("+30 day")); ?>" min="<?php echo date("Y-m-d", strtotime("+1 day")); ?>" required="" />
Issue resolved.
<?php
// If there are any values in the table, display them one at a time.
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
// Asks the qry: Of the last 90 days, what is the most booked day of the week for the current member in session?
// Min date is CURRENT_DATE() -100 instead of CURRENT_DATE() -30, because the MySQL function CURRENT_DATE() prints the date in an int format (YYYYMMDD) with no date formatting. Thus, to get the date a month ago, we must subtract this int by 100 so as to remove 1 from the 6th number in the series of numbers. Which is the 2nd M number.
$sql = "SELECT DATE_FORMAT(tbl_booking.booking_date, '%W'), COUNT(DATE_FORMAT(tbl_booking.booking_date, '%W')) AS mostpopularday
FROM tbl_booking
WHERE tbl_booking.member_ID=$_SESSION[member_ID]
AND tbl_booking.booking_date <= CURRENT_DATE()
AND tbl_booking.booking_date >= CURRENT_DATE() -300
GROUP BY DATE_FORMAT(tbl_booking.booking_date, '%W')
ORDER BY mostpopularday DESC
LIMIT 1";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$recommended_day = $row["DATE_FORMAT(tbl_booking.booking_date, '%W')"];
$date = new DateTime();
$date->modify('next '.$recommended_day);
echo $date->format('Y-m-d');
}
} else {
}
?>

PHP check if event has started

Im using the following mysql script to display a list of active / upcoming fixtures.
Select * FROM schedule
WHERE schedule.gameDate > CURDATE() OR
( schedule.gameDate = CURDATE() and schedule.gameTime > CURTIME() )
GROUP BY schedule.tournament
ORDER By schedule.gameDate
The above script works perfectly.
However, as an additional check to prevent a user from accessing a fixture which has expired im doing the following.
$curTime = date('H:i:s');
$curDate = date('Y-m-d');
$sql = "SELECT * FROM schedule
WHERE tournament = :tour AND weekNum = :round";
$stmnt = $db->prepare($sql);
$stmnt->bindValue(':tour',$tournament);
$stmnt->bindValue(':round', $round);
$stmnt->execute();
$results = $stmnt->fetchAll();
foreach($results as $result){
echo $eventDate = $result['gameDate'];
echo $startTime = $result['gameTime'];
if($curDate > $eventDate){
echo '<h1> CURRENT ROUND ALLREADY STARTED</h1>';
die();
}//if
else if($eventDate==$curDate && $curTime>$startTime){
echo '<h1> CURRENT ROUND ALLREADY STARTED</h1>';
die();
}//else if
}//foreach
My Problem.
The loop never passes the first IF statment which always results to true...
DB Table
When I echo the variables I get the following:
$curTime = 09:30:00
$curDate = 2017-19-03
$eventDate = 2017-03-21
$startTime = 13:00:00
I realize it is not the prettiest code but according to my little experience and logic it should pass both if statments...
Any advise appreciated
Use strtotime() in compare two date in php
Replace if($curDate > $eventDate) with if(strtotime($curDate) > strtotime($eventDate)) and other comparison also
You can convert them to DateTime objects or timestamps to compare. String comparison will only check whether they are equal or not.
So:
$now = new DateTime();
$event = new DateTime($eventDate . ' ' . $startTime);
Then you can check whether dates are equal or later the same way you're already doing. See Example #2 on the Date Diff page of the php website. E.g. $now > $event, etc.
It should be elseif.not else if. There should not be a space between else and if.

Datediff issue - PHP,Mysql

So in my database i've got regdate (date type), but no matter what date it is, the code keeps returning 1.
<?php
$con = mysqli_connect("localhost","root","","login");
if (mysqli_connect_error()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM users");
$row = $result->fetch_array();
$date1 = new DateTime($row['regdate']);
$date2 = new DateTime("now");
$interval = $date1->diff($date2);
echo "It has been " .$interval->d." days ";
//$interval is supposed to be difference between regdate and todays date
I hope I'm not missing something stupid. Thank you for your anwers.
SOLVED
I belive this might be more easier.
SELECT DATEDIFF(NOW(),$row['regdate']);
and I think you need a while loop to find all the records.

current week if date() function and date from mysqli

I have a table containing the following:
StartWeek | StartName |
2012-07-16 | 1 |
What I want to do. Is take the starting week, the current date, and calculate how much time has passed between then and now.
So far I have this:
function getCurrentWeekName() {
$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME);
if (!$mysqli) {
die('There was a problem connecting to the database.');
}
else {
date_default_timezone_set('UTC');
echo "Current date: ".$current_date = date('Y-m-j')."<br>";
$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME);
$query = $mysqli->prepare("SELECT StartWeek FROM Week");
$query->execute();
$query->bind_result($start_date);
while ($query->fetch()){
$start_date = $start_date;
}
echo "start date: ".$start_date."<br>";
echo "time passed: ".$time_passed = strtotime($current_date) - strtotime($start_date)."<br>";
echo "number of days since start: ".$num_of_days = ceil($time_passed/(86400*7))."<br>";
$week_num = ceil($num_of_days/7);
$query = $mysqli->prepare("SELECT StartName FROM Week");
$query->execute();
$query->bind_result($start_name);
while ($query->fetch()){
echo "Start name: ".$start_name = $start_name."<br>";
}
$week_num = $start_name + $week_num;
echo "Week Number: ".$week_num;
}
$mysqli->close();
}
The problem is, this returns the following information:
Current date: 2013-03-18
start date: 2012-07-16
time passed: -1342394787
number of days since start: -2219
Start name: 1
Week Number: -316
So clearly I'm doing it wrong. I think it must be something to do with my time passed calculation, maybe I shouldn't be using strtotime. Can anybody help?
If you're looking for just a difference in days, you can do it directly in MySQL:
SELECT DATEDIFF(now(), StartDate) AS diff_in_days
for other differences, e.g. hours, you can also do things like
SELECT unix_timestamp(now()) - unix_timestamp(start_date) AS seconds
you can do this with php date-diff => http://php.net/manual/en/function.date-diff.php
Check if this you can use:
//replace the values for $startDate and $endDate:
$startDate = strtotime($startDate);
$endDate = strtotime($endDate);
$intervalo = date_diff(date_create($startDate), date_create($endDate));
$out = $intervalo->format("Years:%Y,Months:%M,Days:%d,Hours:%H,Minutes:%i,Seconds:%s");
if(!$out_in_array)
return $out;
$a_out = array();
array_walk(explode(',',$out),
function($val,$key) use(&$a_out){
$v=explode(':',$val);
$a_out[$v[0]] = $v[1];
});
print_r($a_out);

Categories