douzhuochao4027 2015-07-20 18:22
浏览 47
已采纳

单个记录的PHP PDO和访问数据库双重结果

I have an ms access 2010 database with extension *.accdb and I manage to connect to the database using PDO and ODBC driver.

I tried to delete either the *.mdb or *.accdb and get an error, I don't know why it needs both the extensions.

This is the POC:

<?php
$dbName = 'here be path';
$db = new PDO("odbc:DRIVER={Microsoft Access Driver (*.mdb, *.accdb)}; DBQ=$dbName; Uid=; Pwd=;");

$sql = "SELECT MAX(ID) as MaxID from tbl";
$result = $db->query($sql);

foreach($result as $r) {
    var_dump($r);
}

The strange thing is the obtained result:

array (size=2)
  'MaxID' => string '21411' (length=5)
  0 => string '21411' (length=5)

Why do I get 2 entry for one expected result? How can I obtain only this:

    array (size=1)
  'MaxID' => string '21411' (length=5)

The second thing is how can I optimize the PDO to get only one result without foreach?

  • 写回答

1条回答 默认 最新

  • drslez4322 2015-07-20 18:27
    关注

    You get doubled results, because default fetch style is set to PDO::FETCH_BOTH:

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

    So you can call items in the array with the index number or the actual key name.

    $result[0] or $result['MaxID'] will return the same result.
    

    If you don't want duplicates change your style e.g. to PDO::FETCH_ASSOC:

    $result = $db->query($sql);
    $result->fetchAll(PDO::FETCH_ASSOC);
    
    foreach($result as $r) {
        var_dump($r);
    }
    

    More about fetch styles you can find in the documentation.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?