Codeigniter模型:如何使用查询中的值进行进一步计算?

时间:2016-12-19 10:46:33

标签: arrays codeigniter model row

我在具有以下查询的模型中有一个函数,我想在查询之外使用value1,value2和value3进行一些计算。如何从这个结果中获取值()?

function ($id,$username$) {

   $this->db->select("id,value1,value2,value3,value4");
   $this->db->from("table1");
   $this->db->where("username=$username and id = $id");
   $query=$this->get();
   $result = $query->result();

   $result['$testvalue'] = (value1 * value2/113) + value3;

return $result; }
有人可以帮忙吗?我已经找到了如何使用表中的值,但不是查询中的值!

好的,我现在知道如何使用row_array。 我在控制器中调用row_array

$data = $this->model_testmodel->testfunction($id, $username);

...

$this->load->view('pages/view_test', $data);

现在我想知道视图的样子。 我尝试了很多不同的方法。 在我被困的那一刻...

<?php foreach $data as $value: ?>
     <label>Value1:</label>
     <input type="text" name="value1" value="<?php echo $value['value1']; ?>">
     <label>Value2:</label>
     <input type="text" name="value2" value="<?php echo $value['value2']; ?>">
     ...
<?php endforeach; ?>

但我得到两个错误:

  1. 消息:未定义的变量:数据

  2. 消息:为foreach()提供的参数无效

1 个答案:

答案 0 :(得分:0)

试试这个......

function ($id,$username) 
{

   $this->db->select("id,value1,value2,value3,value4");
   $this->db->from("table1");
   $this->db->where(array('id'=>$id,'username'=>$username));
   $query=$this->db->get();
   $result = $query->row();

   $testvalue = (($result->value1 * $result->value2/113) + $result->value3);

   //test here 
   echo $testvalue;
 $res = array();
 $res['testvalue'] = $testvalue;
 $res['value1'] = $result->value1;
 $res['value2'] = $result->value2;
 $res['value3'] = $result->value3;

return $res; 
}

它返回$ res作为array.Easy执行你有问题评论..如果它工作accept.Lets享受..

然后进行函数调用并在变量中接受数组..就像这样.. 首先加载模型然后从你的控制器进行函数调用

$this->load->model('model_name');

$data= $this->model_name->function_name($id,$username);
//Fetch returned array like this..
echo $data['testvalue']; 
echo $data['value1'];
//so on
相关问题