PHP-计算数据库中表的总年数差异

时间:2017-01-25 11:05:11

标签: php date

我想计算年数差异的总数。方案如下: 我在数据库中有一个表。它包含成员的详细信息,包括他们多年的经验。我想获得多年的经验。例如,成员的总年经验是90年。 到目前为止,我已经尝试过,我得到的只是一个成员的经验。

public function getMemberCollectiveExperience() {
        global $config;
        $db = new DatabaseController($config['db']['hostname'], $config['db']['username'], $config['db']['password'], $config['db']['database']);
        $sql = "SELECT * FROM tbl_member WHERE status = 1";
        $result = $db->retrieveRecord($sql);
        if ($result->num_rows > 0) {
            while ($row = $result->fetch_array()) {
                #get member years 
                $memberYears = $row['personal_experience'];
                $currentYear = date('Y');
                $firstResult = $currentYear - $memberYears;
                $total = $firstResult;
            }
            $result = array('count' => $total);
        }
        return $result;
    }

2 个答案:

答案 0 :(得分:1)

您可以尝试这样做以获得所有差异的总和

public function getMemberCollectiveExperience() {
        global $config;
        $total = 0;
        $db = new DatabaseController($config['db']['hostname'], $config['db']['username'], $config['db']['password'], $config['db']['database']);
        $sql = "SELECT * FROM tbl_member WHERE status = 1";
        $result = $db->retrieveRecord($sql);
        if ($result->num_rows > 0) {
            while ($row = $result->fetch_array()) {
                #get member years 
                $memberYears = $row['personal_experience'];
                $currentYear = date('Y');
                $firstResult = $currentYear - $memberYears;
                $total += $firstResult;
            }
            $result = array('count' => $total);
        }
        return $result;
    }

答案 1 :(得分:0)

显然,出于某种原因,我得到了一个暧昧的结果。这是因为我将每个成员的默认个人经验设置为0.因此,在循环中,由于某种原因,它有点看到每个零作为当前年份,2017年。我可能错了。所以我的回答是2108789。 以下代码修复了问题

public function getMemberCollectiveExperience() {
        global $config;
        $total = 0;
        $db = new DatabaseController($config['db']['hostname'], $config['db']['username'], $config['db']['password'], $config['db']['database']);
        $sql = "SELECT personal_experience FROM tbl_member WHERE status = 1";
        $result = $db->retrieveRecord($sql);
        if ($result->num_rows > 0) {
            while ($row = $result->fetch_array()) {
                if ($row['personal_experience'] != null && $row['personal_experience'] != 0) {
                    #get member years 
                    $memberYears = $row['personal_experience'];
                    $firstResult = date('Y') - $memberYears;
                    $total += $firstResult;
                }
            }
            $result = array('count' => $total);
        }
        return $result;
    }

谢谢你们!