Scenario: My PHP application will always use the date field DD-MM-YYYY. MySQL obviously always stores dates in YYYY-MM-DD
Disclaimer: I know how to manually change the date formats – that is not the question
Question: What is a good, clean, elegant way to ensure that my application always retrives the date in DD-MM-YYYY, and mySQL always receives the date in YYYY-MM-DD to be stored.
i.e. Basically I want to have a single place where the conversion occurs automatically, without me having to call it each and every time I do an SQL query. That way it doesnt matter if I “forget” to do a date_conversion – it will just always happen each and every time….
I’m thinking of some sort of callback somewhere?
(edit) My idea: I currently use the Codeigniter framework. I’m thinking of using MY_Model, using before_get, before_insert and before_update callbacks. In these callbacks, I can go through all the fields using something like this for a SELECT:
// {insert my query here to get records from DB. Then:
$query = $this->db->query();
$fields = $query->field_data();
foreach ($fields as $field)
{
if ($field->type == 'date')
// do conversion here
}
and do something similar for an UPDATE/INSERT callback. From what I can tell, there is no extra work on the database (because Codeigniter supplies the information in the $query result)
Thoughts?
edit 2: other idea: just do this for each model, and define which fields are date fields, and just apply the change at each callback… yeah… might do that…?
Ok – answer to my own question – in case people search this and find it:
I am using Jamie’s “MY_Model” – https://github.com/jamierumbelow/codeigniter-base-model
Use callbacks on each of your models which have date fields:
You’ll need to add foreach loops if selecting or adding multiple records. You could make it a generic callback which cycles each variable checking if it is a date – but it seems like alot of overhead. This way you just need to define the date field(s) once for each model