2

I am new to Codeigniter and want to display my state_name which I believe in an array, but I want the first element in that array to be in a variable and be displayed

I am getting the output as: Array ( [0] => stdClass Object ( [state_name] => XYZ state ) ) the output I want is just XYZ state

My controller goes like this:

  public function downloadd()
{   
        $this->load->model('New_model');
        $state_id=$this->input->post('state');   //gets me state_id from my view
        $state_name = $this->New_model->getStatename($state_id); //gets me state_name in form of above output
        print_r($state_name[0]);
        exit;
    }

And here is my model code:

public function getStatename($state_id) {
    
    $this->db->select('state_name');
    $this->db->where('state_id',$state_id);
    $state_name=$this->db->get('states')->result();
    
    return $state_name; //geting users data from db in result array
}

Please tell me where am I going wrong, Thanks for any contribution in advance :)

2 Answers 2

1

Just edit your last two lines of code in your model as follows:

$ans= $this->db->get('states')->row_array();
return $ans['state_name'];

This shall do the needful.

Sign up to request clarification or add additional context in comments.

Comments

0

The result value is a array so you should use row_array to get first row and check if it exists:

public function getStatename($state_id) {
    
    $this->db->select('state_name');
    $this->db->where('state_id',$state_id);

    $row = $this->db->get('states')->row_array();
    if($row)
        return $row['state_name'];
    else {
       //should handle the error since data not found
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.