PHP Mysql 从 foreach 存储的多个值的 PDO 查询以供输出

PHP Mysql PDO query from foreach multiple values stored for output

今天我一直在搜索如何存储来自不同类别注入 4 次的查询的不同值。结果如我所愿,我得到了值,但是当我 return 它们时,我只得到我最后一个查询的结果。 我想知道对于这个问题哪个是好的结果

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)

看起来你在循环中每次都覆盖了最大 ID,如果你想 return 它们全部,它会像这样:

$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