PHP Fatal error: Call to a member function format() on null

Hi

I am getting the error:
PHP Fatal error: Call to a member function format() on null

The code I am using:

<?php
if ($cInfo->gdpr_fz_accept == 0) {
  echo GDPR_NOT_ACCEPTED;
} else {
  $date = \DateTime::createFromFormat('Y-m-d H:i:s', $cInfo->gdpr_fz_accept_date);
  echo GDPR_ACCEPTED . $date->format('d/m/Y H:i');
}
?>

Extra info:
I have two field in database
name — type — lenght — default
gdpr_fz_accept — INT — 1 — 0
gdpr_fz_accept_date — DATETIME — blank — none

Error is reported at the last line

Thank you

Try this to see what is the returned value:

<?php
if ($cInfo->gdpr_fz_accept == 0) {
  echo GDPR_NOT_ACCEPTED;
} else {
  // DEBUG
  // var_dump($cinfo);
  var_dump( $cInfo->gdpr_fz_accept_date );
  die; // halt execution

  $date = \DateTime::createFromFormat('Y-m-d H:i:s', $cInfo->gdpr_fz_accept_date);
  echo GDPR_ACCEPTED . $date->format('d/m/Y H:i');
}
?>

Thank you.
It returns NULL
And the rest of the page fails to load.

NULL != 0.
What is supposed to be setting gdpr_fz_accept?

EDIT: No wait, PHP is supposed to consider null = 0 because it’s the boolean value. is it saying it’s NULL, or is it saying it’s a STRING containing “NULL”?

Try this:

<?php
// remove == 0 and it should catch null and zero. PHP loose type juggling
if ( ! $cInfo->gdpr_fz_accept ) {
  echo GDPR_NOT_ACCEPTED;
  echo '<br>gettype(...) ==> ' .gettype( $cInfo->gdpr_fz_accept );

} else {
  // DEBUG
  // var_dump($cinfo);
  var_dump( $cInfo->gdpr_fz_accept_date );
  die; // halt execution

  $date = \DateTime::createFromFormat('Y-m-d H:i:s', $cInfo->gdpr_fz_accept_date);
  echo GDPR_ACCEPTED . $date->format('d/m/Y H:i');
}
//not required and can cause problems
// ?>

Edit:
Added ! because script incorrect although I far prefer to test for positives rather than negatives. Readability is a lot easier :slight_smile:

Got this:

GDPR_NOT_ACCEPTED
gettype(…) ==> string

@m_hutley

gdpr_fz_accept is supposed to be 1, or 0
1 = accepted
0 = declined (not accepted)

gdpr_fz_accept_date is supposed to be the date it has been accepted.

Looks like you will have to check the script which generates $cInfo

1 Like

Thank you.
It pointed me to the solution, I had missed to add the gdpr_fz_accept_date to the fields to be returned.

Now it works as expected.

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.