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.
Related
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= ...
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.
I need to calculate the time difference between the localDatetime and a Datetime fetched from a specific row in my database-table(csv) called ReportedDateAndTime. I searched a lots of solutions but it doesn't working for me. Displaying localtime & the fetched time from Database are working. But the time difference doesn't. Here is my code so far. Please help. Thanks in advance!
<?php
include_once('connection.php');
$sql="SELECT * FROM csv";
$records=mysqli_query($conn, $sql);
$date = new DateTime(null, new DateTimeZone('Asia/Colombo'));
while ($csv=mysqli_fetch_assoc($records))
{
$exp = $csv['ReportedDateAndTime'];
}
$diff = $date->diff($exp);
echo $diff->format('%H')
?>
From the mysql doc
SELECT CONVERT_TZ('2004-01-01 12:00:00','GMT','MET');
'2004-01-01 13:00:00'
SELECT CONVERT_TZ('2004-01-01 12:00:00','+00:00','+10:00');
'2004-01-01 22:00:00'
https://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html
Thanks all. Fortunately I found an answer. :)
<?php
include 'connection.php';
date_default_timezone_set('Asia/Colombo');
$the_time = date('H:i');
echo $the_time." </br>";
$sql="SELECT ReportedDateAndTime FROM csv";
$result=$conn->query($sql);
while ($row = $result->fetch_assoc())
{
$new_time=$row['ReportedDateAndTime'];
echo "<br/>";
echo $new_time." ReportedDateAndTime</br>";
$datetime1 = new DateTime($the_time);
$datetime2 = new DateTime($new_time);
$interval = $datetime1->diff($datetime2);
$hours=$interval->format('%h');
$minutes= $interval->format('%i');
echo "<br/>";
echo $hours." Hours ".$minutes." Minutes</br></br>";
}
?>
I am trying to switch over from mysql to mysqli as I have been getting a large amount of grief for using mysql to start. I have been looking at examples and thought that I had it right. However, I don't. When I try to add a punch, it doesn't add. I just get a white screen. No error message or the redirect that I request after the punch is added. I have edited the file to hide some sensitive data, but nothing neccessary to trouble shoot. I have looked at the examples multiple times and I can not seem to figure out what is wrong. The punches are added just fine when using mysql. If any one can enlighten me on how to fix this, I would greatly appreciate it. Thank you!
<head>
<title>Process Punch</title>
<body bgcolor="#9966FF">
<link rel="icon" type="image/ico" href="favicon path"/>
</head>
<?php
define('DB_NAME', 'dbname');
define('DB_USER', 'dbuser');
define('DB_PASSWORD', 'dbpass');
define('DB_HOST', 'dhbost');
$link = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if ($link->connect_errno > 0){
die('Could not connect: ' .$link->connect_error);
}
$userid_value = $_POST['userid'];
$punchtype_value = $_POST['punchtype'];
$group_value = $_POST['group'];
$dept_value = $_POST['dept'];
$notes_value = $_POST['notes'];
$table = "tc_".$userid_value;
$unixtime = time();
$unixtime = $unixtime + 3600;
$date_value = date('m/d/Y h:i:s A', $unixtime);
$checkusersql = "SELECT * FROM tc_users WHERE userid = '$userid_value'";
$usercheck = $link->query($checkusersql);
if ($usercheck->num_rows) == 0) {
echo "Sorry, " . $userid_value . " is not a valid user ID. Please try again.";
}else {
$sql = "INSERT INTO $table (time, punchtype, groupname, dept, notes) VALUES ('$date_value','$punchtype_value', '$group_value', '$dept_value', '$notes_value')";
$link->query($sql);
}
header( 'Location: punch path');
$link->close();
?>
Two things:
if ($usercheck->num_rows) == 0)
^-- this one should be removed
has one bracket too many.
Use ($usercheck->num_rows == 0)
As for your date/time issue; you're using m/d/Y h:i:s instead of date("Y-m-d H:i:s")
MySQL is expecting a numeric representation of the format 2014-07-07 19:30:13 as an example.
So do date("Y-m-d H:i:s A") or date("Y-m-d H:i:s") which is why you're getting all zeros.
Use either H or h: (as per the manual)
h - 12-hour format of an hour with leading zeros 01 through 12
H - 24-hour format of an hour with leading zeros 00 through 23
You could leave it the way it is and set your time column to VARCHAR but that would defeat the purpose.
I believe your script is failing on the mysqli query, but you don't have any way of knowing because there is not error reporting in place. Try this and see what it shows.
$checkusersql = "SELECT * FROM tc_users WHERE userid = '$userid_value'";
if (!$usercheck = $link->query($checkusersql)) {
printf("Error: %s\n", $usercheck->error);
}
if ($usercheck->num_rows == 0) {
echo "Sorry, " . $userid_value . " is not a valid user ID. Please try again.";
}else {
$sql = "INSERT INTO $table (time, punchtype, groupname, dept, notes) VALUES ('$date_value','$punchtype_value', '$group_value', '$dept_value', '$notes_value')";
if (!$link->query($sql)) {
printf("Error: %s\n", $link->error);
}
}
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);