今天我一直在搜索如何存储不同类别注入4次的查询的不同值。结果是我想要的,我得到了值,但当我返回它们时,我只得到我最后的查询结果。我想知道这个问题的好结果是什么
public function setMaxId() {
$categorys = $this->getCategorys();
foreach ($categorys as $category) {
$sth = $this->conn->prepare("SELECT MAX(data_id) FROM bcc_data WHERE data_category = '" . $category['bcc_data_category_name'] . "'");
$sth->execute();
$id = $sth->fetchAll();
$maxId = $id[0]['MAX(data_id)'];
var_dump($maxId);
}
}
Var_dump:
string '22' (length=2)
string '35' (length=2)
string '34' (length=2)
string '29' (length=2)
看起来你在每次循环中都覆盖了max id,如果你想全部返回它们,就像这样:
$maxIds = [];
foreach ($categorys as $category) {
$sth = $this->conn->prepare("SELECT MAX(data_id) FROM bcc_data WHERE data_category = '" . $category['bcc_data_category_name'] . "'");
$sth->execute();
$id = $sth->fetchAll();
$maxIds[] = $id[0]['MAX(data_id)'];
}
return $maxIds; //or return max($maxIds) if you just want the single max