title: Codeigniter: Calculate average and display in view
body: <p>I need to calculate in a function the average score of a column named: <code>tot_score</code> from my database table <code>scores_primary</code> I tried some codes but I am not getting anything. Any idea how I can do this?</p>
  
  <h1>Model</h1>
  
  <pre class="lang-php prettyprint-override"><code>function calculateaverage($student_id){
    $query = $this-&gt;db-&gt;select('AVG(tot_score) as  average_score')-&gt;from('scores_primary')-&gt;where('student_id', $student_id)-&gt;get();
      return $query-&gt;row()-&gt;average_score;
  }
  </code></pre>
  
  <h1>Controller</h1>
  
  <pre class="lang-php prettyprint-override"><code>function index(){
    $data['avg'] = $this-&gt;primary_model-&gt;calculateaverage();
    $this-&gt;load-&gt;view('student/studentshow', $data);
  }
  </code></pre>
  
  <h1>View</h1>
  
  <pre class="lang-php prettyprint-override"><code>&lt;span&gt;&lt;b&gt;AVERAGE RESULT:&lt;/b&gt;&lt;?php echo $avg; ?&gt;&lt;/span&gt;
  </code></pre>
  
  <p>I have been on this for days now. I still don't know where the problem lies.
  Average result still shows blank.</p>