1

I'm using the count_all_results() function to return a user's number of languages spoken. But when I try to pass the number to the view, I keep getting a php undefined variable (for $lang_cnt). Below is my code:

Model

function countLanguages($id, $cnt_languages) {
    
    $this->db->where('user_id', $id)->from('languages');
    $cnt_languages = $this->db->count_all_results();
}

Controller

function showLangCount() {

    $data['lang_cnt'] = $this->language_model->countLanguages($cnt_languages);
                        
    $this->load->view('lang_view', $data);
}

View

<p>This user speaks <?php echo $lang_cnt; ?> languages.</p>
0

3 Answers 3

2

One problem is that your model function takes two arguments:

function countLanguages($id, $cnt_languages)

But when you call it you are only passing one argument:

$this->language_model->countLanguages($cnt_languages);

And an even bigger problem, as Rocket points out, is that countLanguages doesn't return anything. Try this:

function countLanguages($id) {
  $this->db->where('user_id', $id)->from('languages');
  return $this->db->count_all_results();
}
Sign up to request clarification or add additional context in comments.

10 Comments

Also, countLanguages doesn't return anything.
@Rocket, thanks, that is indeed the cause of the problem. If you add it as an answer I will upvote and delete mine.
@Mischa - Thanks for your response. I've added the return language as suggested, and removed the 2nd argument. But I'm still getting the same error. I've updated my code to show the changes.
@Rocket - Thanks; I've added the return, but still get the same error. The code in my question has been updated to show the changes.
@chowwy, where is the $id in your controller coming from? Apart from not seeing where $id comes from I don't see any problems with the code you have posted. Could you show your complete code?
|
0

Always check your model functions if they return value or not. Try this:

function showLangCount() {
    if($this->language_model->countLanguages($id))
    {
        $data['lang_cnt'] = $this->language_model->countLanguages($id);
    }
    else
    {
        $data['lang_cnt'] = NULL;
    }

    $this->load->view('lang_view', $data);
}

1 Comment

$this->db->count_all_results(); always returns an integer, so this should not be necessary.
0

Its better to use:

return $query->num_rows();

to return the number of rows effected...

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.