0

I am trying to change the date format before it is displayed with SQL query however the date format is being completely ignored.

my code is

$query = "SELECT * , DATE_FORMAT(formatted, '%d/%m/%Y') from movies;";

then further down this is my table

echo "<table>"

echo "<table border='2'>"
echo "<tr>
<th>id</th>
<th>title</th>
<th>date</th>
</tr>";

while($row = mysql_fetch_array($query))
  {
  echo "<tr>";
  echo "<td>" . $row['id'] . "</td>";
  echo "<td>" . $row['title'] . "</td>";
  echo "<td>" . $row['formatted'] . "</td>";

  echo "</tr>";
  }
echo "</table>";
?>

this query is working, however the date format is being ignored and just displaying the date in yyyy-mm-dd I want it in DD-MM-YY.

thanks

2
  • As a side note, you really shouldn't be doing the formatting in SQL - leave that to your application layer (or even the client side display layer - have JavaScript do it). Formats are culture/locale specific, and your db almost certainly doesn't have the relevant information about the client to know how to display it. For instance, Europeans tend to use MM/DD/YYYY, and if you don't spell it out, they're going to be thinking of the wrong month/day... Commented Mar 9, 2014 at 14:16
  • hmm. Valid point! Ill try working towards that instead! appreciate the input! Commented Mar 9, 2014 at 14:38

2 Answers 2

2

Use an alias to name your calculated column

SELECT * , DATE_FORMAT(datetime, '%d/%m/%Y') AS formatted_date
from movies

Use a different name than the existing column to differ between the two. Then use

echo "<td>" . $row['formatted_date'] . "</td>";

to get the formatted one.

Sign up to request clarification or add additional context in comments.

1 Comment

You sorted this issue in 2 minutes, iv been fighting for around hours!! Appreciate it keep it up!
0

You need to mention the alias for the formatted datetime column other wise formatted value will not be called in your code

SELECT * ,
DATE_FORMAT(`datetime`, '%d/%m/%Y') `datetime`
from movies

4 Comments

I did not down vote it, however i think you might have been down voted due to the ` instead of ' but I understood it. Thanks for the input though.
@user3365549 no bacticks is the standard practice to use in mysql arround db/table/column name
hmm yes with phpmyAdmin, but if you try with html it fails.
@user3365549 in php you can access it as <?php echo $row['datetime']?> without bacticks and never call with backticks in php its a mysql escape

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.