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 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗