jah
jah

Reputation: 1305

manipulating db results in codeigniter

I have some informations in my database that I want to be able to manipulate before passing them to the controller and the view. For example, I have a date of birth that I would like to turn into age.

This is what I have so far:

$sql = ('SELECT username, birthdate, profile_text FROM users WHERE id = ?');

$q = $this->db->query($sql, $this->session->userdata('user_id'));

if ($q->num_rows() === 1) {
    return $q->row();
}

So before returning it, I would like to manipulate the birthdate in the object.

In here I found that if I pass a string as second parameter of row I can use a class to do it. But I have no idea how i would do that and where I would put that class.

I could also get the result as an array with row_array() if that would make the job easier?

Upvotes: 0

Views: 415

Answers (2)

Crowlix
Crowlix

Reputation: 1269

Make a function that converts a birthdate to an age:

public function convertToAge($birthdate){
         $birthDate = explode("/", $birthDate);

         $age = (date("md", date("U", mktime(0, 0, 0, $birthDate[0], $birthDate[1],
       $birthDate[2]))) > date("md") ? ((date("Y")-$birthDate[2])-1):(date("Y")-
$birthDate[2]));
return $age
}

You can set a custom object to resolve your problem like this:

$sql = ('SELECT username, birthdate, profile_text FROM users WHERE id = ?');

$q = $this->db->query($sql, $this->session->userdata('user_id'));

if ($q->num_rows() === 1) {
    $userobject = $q->row();
}
$userobject->birthdate = $this)>convertToAge($userobject->birthdate);
return $userobject

In other parts of your application you can retrieve your userobject and get the birthdate like you do with any other object:

$userobject = $this->model->getuserobject()
$birthdate = $userobject->birthdate

Hope this helps, feel free to ask more questions =)

Upvotes: 2

Mr Sorbose
Mr Sorbose

Reputation: 777

Im not sure if this helps. I would put a little function in model like this:

public function datetoage()
 {
 $birthDate = $datetouse;
         //explode the date to get month, day and year
         $birthDate = explode("/", $birthDate);
         //get age from date or birthdate
         $age = (date("md", date("U", mktime(0, 0, 0, $birthDate[0], $birthDate[1],  $birthDate[2]))) > date("md") ? ((date("Y")-$birthDate[2])-1):(date("Y")-$birthDate[2]));
         return $age;
}

then just apply if to the query data like $age = datetoage($row[birthdate]);

Upvotes: 0

Related Questions