3

I have an array which contains the last 7 days, I loop over that array and every day is stored in $day.

The format looks like this when I echo $day

"2019-09-18"
"2019-09-19"
"2019-09-20"
"2019-09-21"
"2019-09-22"
"2019-09-23"
"2019-09-24"

Now I want to show only the name of the day, so I found this in another SO question:

$string = "2010-11-24";
$date = DateTime::createFromFormat("Y-m-d", $string);
echo $date->format("D") . "<br>";

Which works fine, only when I change the date string into

$string = $day;

I get an error:

Call to a member function format() on boolean

Why is it not working?

My entire code now:

$arr = getLastNDays(7, 'Y-m-d');
foreach($arr as $day) {
    $weekdagen = 'SELECT *
                    FROM orders
                    WHERE DATE(datum) = '.$day.'';
    $weekdagenconn = $conn->query($weekdagen);
    $weekdagen = $weekdagenconn->fetch_assoc();

    $string = "2010-11-24";
    $date = DateTime::createFromFormat("Y-m-d", $string);
    echo $date->format("D") . "<br>";

}
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
  • 1
    Try to `var_dump($day)` before the `DateTime::createFromFormat("Y-m-d", $string);` – fonini Sep 24 '19 at 14:01
  • If that is really what is in `$day` your code should work fine: https://3v4l.org/4lne4 – Nick Sep 24 '19 at 14:02
  • Use prepared statements instead. – freeek Sep 24 '19 at 14:04
  • _The format looks like this when I echo `$day`_ Is that you echoing `$day` from a loop over an array?? – RiggsFolly Sep 24 '19 at 14:06
  • 1
    If possible, post your `getLastNDays()` function – fonini Sep 24 '19 at 14:06
  • Your sql part in your example is not used. Is it how the code looks like? If you won;t use prepared statements you need to wrap the date inside quotes: `$weekdagen = "SELECT * FROM orders WHERE DATE(datum) = '$day'";` – freeek Sep 24 '19 at 14:09
  • before `echo date->format` can you include these lines `$err = DateTime::getLastErrors(); print_r($err);` It is throwing error that is the reason the returned `$date` is a boolean. – Sravanth Pujari Sep 24 '19 at 14:35

0 Answers0