PHP根据数据库中的表计算以年为单位的差异总数
我想计算一下总的年差数。情况如下: 我在数据库中有一个表。它包含成员的详细信息,包括他们多年的经验。我想得到总的经验年数。例如,成员的总工作年限为90年。 到目前为止,我已经尝试过了,我得到的只是一个成员的经验PHP根据数据库中的表计算以年为单位的差异总数,php,date,Php,Date,我想计算一下总的年差数。情况如下: 我在数据库中有一个表。它包含成员的详细信息,包括他们多年的经验。我想得到总的经验年数。例如,成员的总工作年限为90年。 到目前为止,我已经尝试过了,我得到的只是一个成员的经验 public function getMemberCollectiveExperience() { global $config; $db = new DatabaseController($config['db']['hostname'], $confi
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;
}
您可以尝试此操作以获得所有差异的总和
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;
}
显然,出于某种原因,我得到了一个模棱两可的结果。这是因为我将每个成员的默认个人体验设置为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;
}
谢谢大家 所以你们从查询中得到了多条记录@PhpDevNo-idont。我只有一个会员的工作经验。我需要得到所有成员的总年数@B.Desaith这不是我要问的。顺便说一句,据我所知,您必须在数组中存储数据::$total[]=$firstResult;我的错。我误解了你的意思。不,我没有从查询中获取多条记录。我刚试过你的建议。它以数组的形式返回