这些额外的查询结果从何而来?

Where do these extra query results come from?

我正在通过 php/slim api 查询 postgres 数据库。查询本身工作正常,但我得到了无法解释的额外结果。

目标是为更新工具构建一个API。该数据库为每个客户和每个用户保存多个数据集。

相关的 table 看起来像这样:

下面是执行我需要的查询的php函数

function checkVersion($version,$uuid ) {
    $version = strval($version);
    try {
        $pdo = new PDO('pgsql:host=localhost;port=5432;dbname=update;user=postgres;password=12345');
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $sql = "SELECT * FROM client where version = ? and uuid = ?;";
        $prepStm = $pdo->prepare($sql);
        $prepStm->execute(array($version,$uuid));
        $flawless = $prepStm->execute(array($version, $uuid)); // result as bool for some other evaluations
        $queryResult = $prepStm->fetch();
        $results = array(
            "flawless"    => $flawless,
            "queryResult" => $queryResult
        );
        error_log(__LINE__.' '.json_encode($results)); // debugging log
        return $results;
    }
    catch (PDOException $ex) {
        error_log(__LINE__.' '.$ex);
        return $ex;
    }
};

这是记录的结果

"queryResult":{"id":1,"0":1,"uuid":26801208922265,"1":26801208922265,"version":"1.1.0","2":"1.1.0","lastupdate":"01.07.2019","3":"01.07.2019","kunde":1,"4":1}

"id"、"uuid"等预期结果都在,但是哪里多了记录“0”、“1” “2”“3”“4”从何而来?更奇怪的是,它们的值与预期结果完全相同。

我在这里错过了什么?这可能是因为我连续执行了两次语句才发生的吗?

您正在获取额外的值,因为 PDOStatement::fetch is PDO::FETCH_BOTH, which fetches the data indexed by both column name and number. From the manual:

的默认获取模式

PDO::FETCH_BOTH (default): returns an array indexed by both column name and 0-indexed column number as returned in your result set

如果您只需要一组值(例如关联键),请使用 fetch_style 参数 PDO::FETCH_ASSOC 调用 fetch,即

$queryResult = $prepStm->fetch(PDO::FETCH_ASSOC);

就执行两次查询而言,没有必要这样做(只需使用将结果分配给 $flawless 的行)但是因为它是 SELECT 唯一真正的效果将是为了减慢你的代码速度。

你可以试试:

while($arr=$prepStm->fetch()){  
    print_r($arr);  
}