我必须通过从不同的两个表中获取Users_height和users_weight来计算用户的BMI。

这是两个表(http://i.stack.imgur.com/eOQs4.gif)和(http://i.stack.imgur.com/liqhH.gif

期望的输出

  weight_pounds    height_cm
     121.25           130
     132.28           160
     154.32           221
     176.37           434


user_weight表


user_height表


我尝试了此功能,但显示错误:

 function get_all_user_bmi($uid)
{
    $this->load->database();
    $this->db->select('w.weight_pounds','h.height_cm');
    $res = $this->db->order_by('w.uweight_id', 'ASC')->order_by('h.height_id', 'ASC')
            ->get_where('user_weight w',array('w.creater_id'=>$uid))
            ->get_where('user_height h',array('w.creater_id'=>$uid))
            ;
    $ret = array();

    foreach ($res->result_array() as $row) {
        $weight=$row['w.weight_pounds']* 4.88;
        $height=($row['h.height_cm']*0.032808)*($row['h.height_cm']*0.032808);
        $bmi=$weight/$height;
        $ret[] = $bmi;  //final bmi formuala calculated
    }

    return $ret;
}


错误是:

 A Database Error Occurred

Error Number: 1054

Unknown column 'h.height_id' in 'order clause'

SELECT `w`.`weight_pounds` FROM (`user_weight` w) WHERE `w`.`creater_id` = '3235' ORDER BY `w`.`uweight_id` ASC, `h`.`height_id` ASC

Filename: D:\xampp\htdocs\webapp\system\database\DB_driver.php

Line Number: 330


希望有人可以在这里帮助我...

更新

在两列中都添加了额外的列same_id以满足要求,并添加了$this->db->join('user_height h' ,'w.same_id = h.same_id');这段代码,现在可以正常工作了

最佳答案

join尝试一下,您还没有加入表,如果您需要身高,体重等用户详细信息,则在表中应将用户信息和用户ID一起保存在两个表中,因为存在一个-to-关系,然后根据该用户ID加入表以计算用户的bmi

$this->db->select('w.weight_pounds, h.height_cm');
$res = $this->db->join('user_height h' ,'w.user_id= h.user_id')
         ->order_by('w.uweight_id', 'ASC')->order_by('h.height_id', 'ASC')
        ->get_where('user_weight w',array('w.creater_id'=>$uid));


要么

$this->db->select('w.weight_pounds, h.height_cm');
$this->db->from('user_weight w');
$this->db->join('user_height h' ,'w.user_id= h.user_id')
$this->db->where('w.creater_id',$uid);
$this->db->where('h.creater_id',$uid);
$this->db->order_by('w.uweight_id', 'ASC')->order_by('h.height_id', 'ASC')
$query = $this->db->get();


在循环中,只需使用列名

foreach ($res->result_array() as $row) {
        $weight=$row['weight_pounds']* 4.88;
        $height=($row['height_cm']*0.032808)*($row['height_cm']*0.032808);
        $bmi=$weight/$height;
        $ret[] = $bmi;  //final bmi formuala calculated
    }


Reference Active record

关于php - 如何在一个函数中执行两个表列数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18803289/

10-13 00:52