Call to a member function modify() on a non-object - php

So I'm trying to check if the reset link is expired. Here's what I got
//Get token data
$stmt = $con->prepare("SELECT token_created_at from reset WHERE token = :urltoken");
$stmt->bindValue(':urltoken', htmlspecialchars($_GET['token'], ENT_QUOTES, 'UTF-8'));
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
while($row = $stmt->fetch()) {
$token_created_at = $row['token_created_at'];
}
$token_created_at;
//Return current time to match
$current_time = new DateTime();
$my_dt = DateTime::createFromFormat('m-d-Y H:i:s', $token_created_at);
//Modify error
$expires_at = $my_dt->modify('+1 hour');
And how I set the date when the user asks for a reset
//Get creation time
$time_gen = date('m-d-Y H:i:s', time());
Now what happens is I get
Fatal error: Call to a member function modify() on a non-object in /Users/MATT/Desktop/Learn/forgot/activate.php on line 26
Line 26 being
$expires_at = $my_dt->modify('+1 hour');
Any ideas? I've tried other posts, but they don't seem to apply to my issue. They're also stored as VARCHAR

According to the PHP docs:
DateTime::createFromFormat Return Values
Returns a new DateTime instance or FALSE on failure.
So your $my_dt variable is very likely FALSE, which would definitely cause that error.
Your time format string probably needs to be 'Y-m-d H:i:s' if you're using the standard MySQL DATETIME type.

Related

Trying to add 2 dates with DateTime Object PHP

Hi there and thank you for the help. I will try to be breef.
I have a SQL table with one col named "duration" -> type Time
I need to get this "duration" and add to the actual DateTime -> date()
Till now I got something like these:
$id_mission = $_POST["id_mission"];
$sql="SELECT duration FROM missions WHERE id_mission='".$id_mission."'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
How do i pick this: $row['duration'] and convert to DateTime Object?
$date = new DateTime();
$get_datetime = $date->format('Y-m-d H:i:s');
$get_datetime->add(new DateInterval($row['duration']));
I got these sql error:
Fatal error: Call to a member function add() on string in C:\wamp64\www\players\actions\insert_mission.php on line 18
This line converts your DateTime object into a string which you are then trying to call the add() method with. Strings don't have this method.
$get_datetime = $date->format('Y-m-d H:i:s');
To add the date from your row don't use the format method.
$date = new DateTime();
$date->add(new DateInterval($row['duration']));
The error message that you are seeing has nothing to do with SQL, it is telling you that your are trying to treat a string like an object. Which doesn't work in PHP.

Calculate difference between time in DB and Current Time

First off - I am using the MySQLi Procedural method of using MySQL via PHP
I am trying to create a way click a button to set a "timer". From what I understand, the best way to do this (on a dynamic timer - IE: 5 minutes from click) is to calculate what the time() would be 5 minutes from "now".
I want to save this to a DB in case the user disconnects from the page and reconnects (username/password login). This way, when they log back in, it would keep their remaining time.
Now for the code:
I am using this to pull my DT variable from SQL (YYYY-MM-DD HH-MM-SS):
$expirationTime = new DateTime();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$expirationTime = $row['workTimer'];
}
}
$time = strtotime($expirationTime);
$expirationTime = date("Y-m-d H:i:s", $time);
Then I pull the current time:
$currentTime = date('Y-m-d H:i:s');
I have done echos on both of these and they are displaying correctly. What I want to do now is figure out the difference. I have tried multiple ways of doing this, but nothing seems to work. Most recently I did:
$countdown = $currentTime->diff($expirationTime);
$countdown = $countdown->format("Y-m-d H:i:s", $countdown);
with an error of Fatal error: Call to a member function diff() on a non-object in...
What might be the problem?
Thanks!
I have updated some of the codes per the comment's suggestions to:
$currentTimeT = date('Y-m-d H:i:s');
$currentTime = strtotime($currentTimeT);
$time = date("Y-m-d H:i:s", $expirationTime);
$expirationTime = strtotime($expirationTime);
$countdown = $currentTime->diff($expirationTime);
$countdown = $countdown->format("Y-m-d H:i:s", $countdown);
echo "C ".$currentTime."<br/> E ".$expirationTime."<br/>D ".$countdown;
Same Error.
It is likely the least elegant solution but you could cut your to timestrings both into "d,m,y,h,i,s"-substrings and feed them to http://php.net/manual/de/function.mktime.php. Then you calc the difference of the timestamps.
date_diff — Returns the difference between two DateTime objects
and you are passing non-object to function diff()
See this PHP manual
I solved your issues on my side give it a try:
$time = "2016-09-1 04:45:54";
$time = strtotime($time);
$currentTime = new DateTime(date('Y-m-d H:i:s'));
$expirationTime = new DateTime(date("Y-m-d H:i:s",$time));
$countdown = $currentTime->diff($expirationTime);
$countdown1 = $countdown->format("%H:%I:%S");
print_r($countdown1);die;

Call to a member function format() on a non-object DateTime

This problem might be common but it seems like I can't find out what I did wrong.
I have two variables the date and time from database which I think is in UTC format and I need to convert to AEST;
$date = message['date']; //25/09/2014
$time = message['time']; //9:00:00
$combined_time = $date . " " . $time;
$schedule_date = DateTime::createFromFormat("Y-m-d H:i:s",$combined_time ,new DateTimeZone("Australia/Melbourne"));
return $schedule_date->format("jS-A-Y H:i:s T");
I got Call to a member function format() on a non-object exception.
You should use ("d/m/Y h:i:s"):
$schedule_date = DateTime::createFromFormat("d/m/Y h:i:s", $combined_time , new DateTimeZone("Australia/Melbourne"));
The given format is wrong because your date-time is as 25/09/2014 9:00:00. Check this example.
You are not creating any object of class so giving you error you need to create class object or use directly.
$schedule_date = new DateTime($date);
return $schedule_date->format("jS-A-Y H:i:s T");
or you need to pass correct format in Datetime() see #The Alpha answer for this
For more read manual :- http://php.net/manual/en/datetime.createfromformat.php
// convert string to timestamp
$timeStamp = strtotime($combined_time);
// create DateTime object use timestamp
$date = new DateTime();
$date->setTimestamp($timeStamp);
Then you can use $date->format('Y') to get year...

Error in PHP $date2 = $date1->format('Y-m-d')

I get the following error:
PHP Fatal error: Call to a member function format() on a non-object
in code:
$date = new DateTime();
$date1 = $date->modify('-6 months');
$date2 = $date1->format('Y-m-d');
I want to get this date of 6 months before from now and delete all entries in database which are earlier than this 6 months date:
$query = $conn->prepare("DELETE FROM files WHERE files.date < ?");
$query->bind_param('s', $date2);
$query->execute();
In MySQL "date" field is in files table of datatype "timestamp" whose value is "CURRENT_TIMESTAMP" stored by MySQL as default when a row is created.
This code get you 6 month ago from now:
date('Y-m-d', strtotime('now -6 month'))
EDIT:
and use DateTime:
echo (new DateTime('-6 months'))->format('Y-m-d');
try below code:
<?php
$date = new DateTime('-6 months');
echo $date2 = $date->format('Y-m-d');
?>
It appears you are using an outdated version of php.
Starting with php 5.3+ DateTime::modify returns the datetime object is was called upon prior to that null was returned.
You don't need to assign the result of modify to a new variable as it modifies the current object and does not return a new one.
To make it work on 5.2:
<?php
$date = new DateTime();
$date->modify('-6 months');
$dateS = $date->format('Y-m-d');
var_dump($dateS);
You should however update your php to a supported version.
PHP 5.4+ short-example:
$dateS = (new DateTime('-6 months'))->format('Y-m-d');
Seems like the call to
$date->modify('-6 months');
encounters an error and does not return a DateTime instance but probably false (see documentation).
Which PHP version are you using? I could not reproduce that error with the given example on PHP 5.5.9
Maybe you could just use the strtotime function
EDIT:
I took the Wayback Machine from Internet Archive and found that older versions of PHP ( i.e. 5.1.0) returned NULL instead of the DateTime object: see for yourself. In that case it seems like you apply the modification on your date directly so you need to change your code to
$date = new DateTime();
$date->modify('-6 months');
$dateString = $date->format('Y-m-d');
$query = $conn->prepare("DELETE FROM files WHERE files.date < ?");
$query->bind_param('s', $dateString);
$query->execute();

PHP DateTime __construct() Failed to parse time string (xxxxxxxx) at position x

I had this construction error when trying to creating a new DateTime object using a timestamp:
Exception: DateTime::_construct(): Failed to parse time string (1372622987) at position 8 (8): Unexpected character in DateTime->_construct()
The object creation code is:
$start_date = new DateTime( "#{$dbResult->db_timestamp}" );
Where $dbResult->db_timestamp is a valid unix timestamp taken from a database. The timestamp in question was:
1372622987
I would understand this error for invalid formats being passed, but this is a genuine timestamp.
The reason this is very strange: I since ran a script to create a new DateTime object with the timestamp passed in as a hard coded value, and it reported no errors.
This seems to have been a one off, but I need an explanation if there is one, as I can't afford for this to happen again.
You should use setTimestamp instead, if you hardcode it:
$start_date = new DateTime();
$start_date->setTimestamp(1372622987);
in your case
$start_date = new DateTime();
$start_date->setTimestamp($dbResult->db_timestamp);
Use the createFromFormat method:
$start_date = DateTime::createFromFormat("U", $dbResult->db_timestamp);
UPDATE
I now recommend the use of Carbon
change your code to this
$start_date = new DateTime( "#" . $dbResult->db_timestamp );
and it will work fine
This worked for me.
/**
* return date in specific format, given a timestamp.
*
* #param timestamp $datetime
* #return string
*/
public static function showDateString($timestamp)
{
if ($timestamp !== NULL) {
$date = new DateTime();
$date->setTimestamp(intval($timestamp));
return $date->format("d-m-Y");
}
return '';
}
$start_date = new DateTime();
$start_date->setTimestamp($dbResult->db_timestamp);

Categories