0

I'm trying to get data from my mariaDB table using a SQL Statement with where and datetime field. When I enter the string like Datum >= "2018-01-18 15:16:17" the result is as expected. When I compare the variable Datum >= $ymdt I receive a blank page. I tried different delimiters ('") for the string. I tried with other fields like City successful. Where is my problem with this datetime?

<?php

$dat="2018-01-25 15:16:17"; 
$ymdt = DateTime::createFromFormat('Y-m-d H:i:s', $dat)->format('Y-m-d H:i:s');

echo "<p> Debug Section<br>";
echo $dat;
Output: 2018-01-25 15:16:17
echo "<br>";
echo $ymdt;
Output: 2018-01-25 15:16:17
echo "</p>";

this following line returns a blank table, why?

foreach($db->query("SELECT * FROM wetterdaten where datum >= $ymdt ORDER BY id DESC") as $zeile) {}

this following line returns the table filled from date (datetime field mysql) as expected

foreach($db->query("SELECT * FROM wetterdaten where datum >= '2018-01-25 15:16:17' ORDER BY id DESC") as $zeile) {}
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141

1 Answers1

1
foreach($db->query("SELECT * FROM wetterdaten where datum >= $ymdt ORDER BY id DESC") as $zeile) {}

this line returns a blank table, why?

Because in this example, your date/time string is not quoted. This query will be filled like:

where datum >= 2018-01-25 15:16:17

You need to wrap your $ymdt variable in single quotes:

foreach($db->query("SELECT * FROM wetterdaten where datum >= '$ymdt' ORDER BY id DESC") as $zeile) {}

A better solution would be to use a prepared statement, that way you don't have to worry about quoting and escaping strings yourself.

rickdenhaan
  • 10,857
  • 28
  • 37
  • wow, quick Response. Thanks, that's working. Beginners problems .... –  Jan 27 '18 at 15:13