phpmysqlcodeigniterselectmodel

How to execute raw SQL and return the result set from a CodeIgniter model method


I am using CodeIgniter framework for a project. I have a controller which is calling the data from a model function. Here is the controller.

public function getThirdPartyRR($token)
{
    if ($this->input->is_ajax_request()) {
        // $data = json_decode(file_get_contents('php://input'), true);
        // Following is loaded automatically in the constructor.
        //$this->load->model('user_profile');
        $userid = $this->myajax->getUserByAuth($token);
        if ($userid) {
            $this->load->model("riskrating_page");
            /* If we have an impersonated user in the session, let's use him/her. */
            if (isset($_SESSION['userImpersonated'])) {
                if ($_SESSION['userImpersonated'] > 0) {
                    $userid = $_SESSION['userImpersonated'];
                }
            }
            // $resultList value could be null also.
            $result = $this->riskrating_page->getThirdPartydata($userid);             
            /* Little bit of magic :). */
            $thirdpartylist = json_decode(json_encode($result), true); 
            $this->output->set_content_type('application/json');
            $this->output->set_output(json_encode($thirdpartylist));
        } else {
            return $this->output->set_status_header('401', 'Could not identify the user!');
        }
    } else {
        return $this->output->set_status_header('400', 'Request not understood as an Ajax request!');
    }   
}

And here is the query function in the model where I get the data from.

public function getThirdPartydata($id)
{ 
    $query = 'SELECT b.text_value as Company, a.third_party_rr_value
              FROM user_thirdparty_rr a 
              inner join text_param_values b
                  on a.third_party_rr_type = b.text_code and
                  b.for_object = \'user_thirdparty_rr\'
              WHERE a.Owner = '.$id. ' and 
                  a.UPDATE_DT is null;';      
}

But when I debug it using Netbeans, it shows that in my controller in the $result function I get null - meaning I couldn't grab any data from MySQL.

Here is the search result from MySQL. result


Solution

  • You only write your query not fetch any data from your query result

    public function getThirdPartydata($id): array
    {
        $query = "
            SELECT b.text_value as Company, a.third_party_rr_value
            FROM user_thirdparty_rr a 
            INNER JOIN text_param_values b
                ON a.third_party_rr_type = b.text_code
                    AND b.for_object = 'user_thirdparty_rr'
            WHERE a.Owner = ?
                AND a.UPDATE_DT is null
        ";
        $this->db->query($query, [$id]); // execute your query
        return $query->result_array(); // fetch data
    }