[英]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. 所以在返回之前,我想操纵对象中的
birthdate
。
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? 我还可以将结果作为带有
row_array()
的数组获得,如果这样可以使工作更轻松?
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并像使用任何其他对象一样获取生日:
$userobject = $this->model->getuserobject()
$birthdate = $userobject->birthdate
Hope this helps, feel free to ask more questions =) 希望这有帮助,随时提出更多问题=)
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]); 然后只需将if应用于$ age = datetoage($ row [birthdate])等查询数据;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.