-3

I have a query like this

select fname,joined_date from employees where id=1

currently the date format I'm using to display this returned employee details is Y-m-d. But now I need to convert the default mysql format Y-m-d to d/m/Y(in all date information display fields).

For me it's very very difficult to go through all the files to do the date format conversion.

So I thought of doing some thing like this in my database class.I have a function like this in my database class

function fetch($res){
   $row = mysql_fetch_assoc($res);
   foreach($row as $key=>$value){
   if(preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/',$value))
      $row[$key] = date('d/m/Y',strtotime($value));
   }
   return $row;
}//end function

and i'm using this function like this

$row = $db->fetch($res);

or

while($row = $db->fetch($res)){...}

I'm getting the expected output,but with an error message

invalid argument for foreach

it looks like the fetch function code executed (total_num_rows + 1) times

If I use for loop instead of foreach, getting undefined offset error

currently I'm using some thing like this to escape

if(is_array($row)){...}

when i look for the type $res, it showed resource(1st iteration),resource(2nd)

for $row array

array(1st iteration),boolean(2nd)

Can anybody tell me why it's happening? Or is there a better way to do this?

Thanks in advance.

Vipin Kumar KM
  • 356
  • 5
  • 17

3 Answers3

1

When you reach the end of the results, mysql_fetch_assoc() returns false. You need to check for that case:

function fetch($res){
   $row = mysql_fetch_assoc($res);
   if ($row) {
     foreach($row as $key=>$value){
       if(preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/',$value)){
          $row[$key] = date('d/m/Y',strtotime($value));
       }
     }
   }
   return $row;
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

if you want this format for ex: June 19, 2015 use this: date("F d, Y",strtotime($myrow['date'])); where $myrow['date'] is what you are fetching from mysql row wise check this link for further assistance: http://erikastokes.com/mysql-help/display-mysql-dates-in-other-formats.php

ohsoifelse
  • 681
  • 7
  • 6
  • Could you please elaborate more your answer adding a little more description about the solution you provide? – abarisone Jun 19 '15 at 07:18
-1

It is easier to have you convert the date to the desired format already in the MySQL command. example:

SELECT *, DATE_FORMAT(date, "%m-%d-%y") AS date FROM my_table;
hichris123
  • 10,145
  • 15
  • 56
  • 70