-1

In my database I have a date column (type = date). On of the values is this column is '2022-04-29'. When I try to get this date I get an error "Uncaught Error: Call to a member function format() on string".

The code I use:

if ($vrijedag_result = mysqli_query($conn, "SELECT * FROM vrijedagen WHERE datum BETWEEN '$VrijeDagenDatum1' AND '$VrijeDagenDatum2'")) {
    if (mysqli_num_rows($vrijedag_result) > 0) {
        $vrijedagArray = array();
        while ($vrijedagenRij = mysqli_fetch_array($vrijedag_result)) {
            $vrijedagdatum = $vrijedagenRij['datum'] -> format('Y-m-d');
            array_push($vrijedagArray, "" . $vrijedagdatum . "");
        }
    }
    else {
        $vrijedagArray = "";
    }
    mysqli_free_result($vrijedag_result);
}

In my database the columntype is 'date' and the value I see in PHPMyAdming is 2022-04-29. This value is written to my DB via another php script.

When I try to see the value I receive from my script (using JavaScript Alert) I get '1989'...which is a total of 2022 minus 4 minus 29...

Can somone explane what I'm doing wrong? Does someone have a solution? Thanks in advance!

Edit 1: The error comes on the line '$vrijedagdatum = $vrijedagenRij['datum'] -> format('Y-m-d');'

Joete
  • 39
  • 8
  • **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/32391315) – Dharman Apr 10 '22 at 13:04

1 Answers1

1

You should replace this line:

$vrijedagdatum = $vrijedagenRij['datum'] -> format('Y-m-d');

With:

$date = new DateTime($vrijedagenRij['datum']);

$vrijedagdatum = $date->format('Y-m-d');

Or with:

$vrijedagdatum = date_format(date_create($vrijedagenRij['datum']), 'Y-m-d');
Dori Rina
  • 364
  • 2
  • 7