Jump to content

Format dates in php


kahodges

Recommended Posts

I am having some trouble getting the code below to pull dates from a database and echo:

mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");
$query="SELECT nickname, last_name, date_format(BirthDate,"%m/%d/%Y"), QuitDate FROM employees WHERE QuitDate is null AND MONTH(BirthDate) = MONTH(DATE_ADD(CURDATE(),INTERVAL 1 MONTH));";
$result=mysql_query($query);
$num=mysql_numrows($result);
mysql_close();
?>
<table border="0" cellspacing="2" cellpadding="2">
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<?php
$i=0;
while ($i < $num) {

$f1=mysql_result($result,$i,"nickname");
$f2=mysql_result($result,$i,"last_name");
$f3=mysql_result($result,$i,"date_format(BirthDate,"%m/%d/%Y")");
?>

 

It throws the error: Parse error: syntax error, unexpected '%'. But, the above query is valid and works in phpMyAdmin. Any help would be appreciated.

Thanks in advance.

Link to comment
https://forums.phpfreaks.com/topic/194844-format-dates-in-php/
Share on other sites

"date_format(BirthDate,"%m/%d/%Y")"
^- start string
                       ^- end string
                                ^- start string
                                  ^- end string

 

What you have is a MySQL string enclosed in a PHP string.  When you start doing these types of things you have to be careful of how you nest strings.

 

Either of these might work:

"date_format(BirthDate,\"%m/%d/%Y\")"
'date_format(BirthDate,"%m/%d/%Y")'

 

Taking it further, your original code is exactly the same, syntactically, as if you had typed:

"string1" %m/%d/%Y "string2"

Which is not valid PHP code.

Link to comment
https://forums.phpfreaks.com/topic/194844-format-dates-in-php/#findComment-1024537
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.