PHP MYSQL PDO SUM of columns

前端 未结 3 953
生来不讨喜
生来不讨喜 2021-01-13 03:48

I\'m new to php and I\'ve searched for the past hour and read all the documentation I could find and nothing is helping. I have a table that has a bunch of rows of data. I\'

相关标签:
3条回答
  • 2021-01-13 03:57

    You can use SUM() without explicitely grouping your rows because if you use a group function in a statement containing no GROUP BY clause, it is equivalent to grouping on all rows.

    If however you want to use the SUM() function for something slightly more complicated you have to group your rows so that the sum can operate on what you want.

    If you want to get multiple sums in a single statement, for example to get the distance for all users at once, you need to group the rows explicitely:

    $res1 = $db->prepare("
        SELECT
            SUM(distance) AS distance,
            user_id
        FROM trip_logs WHERE status = '2'
        GROUP BY user_id
    ");
    $res1->execute();
    while ($row = $res1->fetch(PDO::FETCH_ASSOC))
    {
        echo "user $row[user_id] has runned $row[distance] km.\n";
    }
    

    This will return the sum of distances by user, not for all users at once.

    0 讨论(0)
  • 2021-01-13 04:03

    Try this if you are using a Class :

        class Sample_class{
    
            private $db;
    
            public function __construct($database) {
                $this->db = $database;
            }   
    
            public function GetDistant($user_id,$status) {
    
                        $query = $this->db->prepare("SELECT sum(distance) FROM trip_logs WHERE user_id =? AND status =?");
    
                        $query->bindValue(1, $user_id);
                        $query->bindValue(2, $status);
    
                        try{ $query->execute();     
    
                         $rows =  $query->fetch();
                         return $rows[0];
    
                  } catch (PDOException $e){die($e->getMessage());}  
                } 
        }
    
    $dist = new Sample_class($db);
    
    $user_id = 10;
    $status = 2;
    
    echo $dist->GetDistant($user_id,$status);
    
    0 讨论(0)
  • 2021-01-13 04:18

    You're only returning one row in this instance. Modify your summed column to have an alias:

    SELECT SUM(distance) AS totDistance FROM trip_logs ....
    

    Now you can can fetch the row -

    $row = $res1->fetch(PDO::FETCH_ASSOC);
    echo $row['totDistance'];
    

    No need to loop.

    0 讨论(0)
提交回复
热议问题