Why variable is returing only 1 instead of sum of values from the all rows of my table?

I am trying to get the sum of available values of all rows what a column contains. using SQL query from “commandline” it is working and getting the result but when I am trying to keep it in a PHP variable and show, it returns only 1 as a result! what the wrong I am doing?


public function getObMarks(){
            $query = "SELECT SUM(obMarks) FROM ques_ans_marks";
            $getMarks = $this->db->select($query);
            $getObMarks = $getMarks->num_rows;
            return $getObMarks;
        } 

It’s hard to say for sure without knowing what database library you’re using, but num_rows sounds like it’s the number of rows in the result. You’re asking for an aggregated result - the sum of a column - so there’s only going to be one row. That’s where your 1 comes from.

You need to look at the documentation of your database library and find how to get a single row from a result; that’s where you’ll find your number.

1 Like

Sometimes, when we have a thought in our heads, it’s hard to realize that we are being ambiguous. When that happens to me, I try to be more explicit.
Try this:

public function getObMarks(){
  $query = “SELECT SUM(obMarks) AS ObMarks FROM ques_ans_marks”;
  $getMarks = $this->db->select($query);
  $getObMarks = $getMarks->ObMarks;
  return $getObMarks;
}

1 Like

Thank you both @skawid and @calgeorge I have done the following. and soloved- I had to use fetch_row(); instead of num_rows()
I had to apply

public function getObMarks(){ 
$userid	=Session::get("userid"); 
$query = "SELECT SUM(obMarks) FROM ques_ans_marks WHERE userid='$userid'"; 			
$getMarks = $this->db->select($query); 			
if ($getMarks->num_rows > 0){                                          
$getObMarks = $getMarks->fetch_row();                                          
return $getObMarks[0];                                        
                                             } else  			                                
 {  return $getObMarks=0;       } 
			 	   }  
Sponsor our Newsletter | Privacy Policy | Terms of Service