MySQL PDO fetchAll为具有整数索引的数组

hjp*_*r92 6 php pdo pdostatement

我有一个有两列的表.表:ctgtable和列:idctg.由于我完全从以前的mysql_*功能转移到PDO,我面临一些愚蠢的错误(或者可能缺乏知识).

我想将整个表的ctg列(总共最多20行)选择为具有整数索引的数组.

我的方法

在我看来,最接近的解决方案是:

<?php
    $sth = $dbh->prepare("SELECT id, ctg FROM ctgtable");
    $sth->execute();
    /* Fetch all of the values of the second column */
    $result = $sth->fetchAll(PDO::FETCH_COLUMN, 1);
    var_dump($result);
?>
Run Code Online (Sandbox Code Playgroud)

对于相同的结果,还有其他更短/更好的替代方案吗?或者这是获取结果的最佳/唯一可能方法.

样本表

id      ctg
01     movie
27       tv
64     sports
Run Code Online (Sandbox Code Playgroud)

等等

样本结果

Array( 1 => "tv",
    2 => "movie",
    3 => "anime",
    4 => "game",
    5 => "telugu"
);
Run Code Online (Sandbox Code Playgroud)

索引可以从0开始,也可以不从0开始.对我来说无关紧要.我试着寻找这样一个可能的问题,但似乎没有一个问题与我的问题相关.

Mad*_*iha 6

你有的方法很好.虽然如果您不需要ID,为什么还需要查询它?

<?php
    $sth = $dbh->prepare("SELECT ctg FROM ctgtable");
    $sth->execute();
    /* Fetch all of the values in form of a numeric array */
    $result = $sth->fetchAll(PDO::FETCH_ARRAY);
    var_dump($result);
?>

对MySQL的较少限制导致较少的处理时间,最终导致更好的结果.

  • PDO :: FETCH_ARRAY是非标准的PDO常量.请参阅http://php.net/manual/en/pdostatement.fetchall.php和http://www.php.net/manual/en/pdostatement.fetch.php某些系统支持PDO :: FETCH_ASSOC.PDO :: FETCH_COLUMN是首选. (4认同)