Multiple MySQL Queries in 1 Function in Model

末鹿安然 提交于 2020-01-06 08:03:58

问题


  1. Is it possible to run 2 MySQL Queries (select AVG and then Update) in a Function ?
    1. How to print / echo the current error by using : $this->db->error(); OR $this->db->last_query(); ?
    2. My code contain a MySQL Sub Query, is there any wrong syntax?

This below code seems like not working. I am trying to get an average value from the first query and then use the query as a field to store (update) to database. Please help..

public function updateReprob(){
    $id = $this->input->post('txtId');
return $rata2 = $this->db->query('SELECT AVG(harian) a from (select harian from sla limit 3) b');

    $field = array(
    'harian' => $this->input->post('nameharian'),
    'bulanan' => $rata2
    );

    $this->db->where('id', $id);
    $this->db->update('sla', $field);
    if($this->db->affected_rows() > 0){
        return true;
    }else{
        return false;
    }
}

回答1:


You have error in your way of getting result. take a look at below code

public function updateReprob(){
    $id = $this->input->post('txtId');
    $rata2 = $this->db->query('SELECT AVG(harian) a from (select harian from sla limit 3) b')->row();

    $field = array(
      'harian' => $this->input->post('nameharian'),
      'bulanan' => $rata2->a
    );

    $this->db->where('id', $id);
    $this->db->update('sla', $field);
    if($this->db->affected_rows() > 0){
        return true;
    }else{
        return false;
    }
}

Hope it help you!



来源:https://stackoverflow.com/questions/52272826/multiple-mysql-queries-in-1-function-in-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!