Chris Chris - 6 months ago 9
SQL Question

Dislpay correct DateTime from db in php

So I'm having a problem with the date time presentation.
I want to display the time of entries into db in a list with title of the entry next to it.
But at the moment, whenever I try to format the time properly, the code only displays one entry instead of all of them.
Can anyone help me ?

<?php
$result = mysql_query("SELECT * FROM posts");

while ($row = mysql_fetch_array($result)){
echo "<li>{$row["date"]}". "&nbsp; &nbsp; &nbsp; &nbsp;". $row["title"]. "</li>";
}
?>


like this it obviously just shows whats in the db :

2014-09-08 07:09:24.476246 this is it !!
2014-09-05 06:20:20.317560 So nun endlich die Website online


but when I format the dates somehow like this ...

<?php
$result = mysql_query("SELECT * FROM posts");

$new_date = mysql_fetch_row($result);
$date = date_create($new_date[3]);

while ($row = mysql_fetch_array($result)){
echo "<li>". date_format($date, 'Y-m-d H:i:s'). "&nbsp; &nbsp; &nbsp; &nbsp;". $row["title"]. "</li>";
}
?>


I only get the last row from the db.

Answer

Try to format with date() directly in loop so no need to $date var

echo "<li>".date('Y-m-d H:i:s', strtotime($row["date"]))."&nbsp; &nbsp; &nbsp; &nbsp;". $row["title"]. "</li>";

or just make your

 $date = date_create($new_date[3]);

inside the loop

Also mysql_* has been deprecated for more follow @john Conde answer.

Comments