Rengee Rengee - 6 months ago 82
SQL Question

PHP Fatal error: Call to a member function diff() on a non-object in... comparing DateTime from database

Im trying to compare two different DateTime and get the difference.

Im getting this error PHP Fatal error: Call to a member function diff() on a non-object in... when trying to run/compile my code but cant figure out what I'm doing wrong.

$datetime = date("Y-m-d H:i:s");
$localhost = "localhost";
$conn = mysqli_connect($localhost, $mysqlUsername, $mysqlPassword, $mysqlDB);

if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());
echo "Connection to DB failed";
}

$sql = "SELECT * FROM UniqueUsers";
$result = mysqli_query($conn, $sql);

if ($result->num_rows > 0 )
{
while($row = $result->fetch_assoc())
{
$datetime1 = new DateTime($row['worldtime']);
$interval = $datetime->diff($datetime1);
echo $interval->format('%R%a days');
}
}

S K S K
Answer

Your $datetime variable is not an object. Function date() doesn't return a DateTime object, but a formatted string.

Replace your first line with

$datetime = new DateTime(date("Y-m-d H:i:s"));