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.

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

报告相同问题?

悬赏问题

  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄