使用PDO获取数据,并且只获取一次带有列名的数据


Fetching data using PDO and get the data only once with its column names

当使用PDO从mysql数据库中获取值时,我会得到一些冗余信息,我想知道为什么。下面的php函数返回我希望返回的值。但如果我返回结果数组,我会得到双倍的值。

public function getNames($userid) {
        try {
            $dbh = new PDO('mysql:host=localhost;dbname='.parent::Database(), parent::User(), parent::Password());
        } catch (PDOException $e) {
            var_dump("error: $e");
        }
        $sql = "SELECT ID, Name FROM cars WHERE userid =:UID and type=2";
        $sth = $dbh->prepare($sql);
        $sth->bindParam(':UID', $userid);
        $sth->execute();
        $result = $sth->fetchAll(); //fetches all results where there's a match
        $result2 = array();
        foreach($result as $res)
            $result2[] = array("ID"=>$res["ID"], "Name"=>$res["Name"]);
        return $result2;
    }

$Result返回:

Array
(
    [0] => Array
        (
            [ID] => 2
            [0] => 2
            [Name] => Volvo
            [1] => Volvo
        )
    [1] => Array
        (
            [ID] => 8
            [0] => 8
            [Name] => Ford
            [1] => Ford
        )
)

$Result2返回:

Array
(
    [0] => Array
        (
            [ID] => 2
            [Name] => Volvo
        )
    [1] => Array
        (
            [ID] => 8
            [Name] => Ford
        )
)

为什么$result会这样?这就像它多次获取我的数据。我用错代码了吗?如果可能的话,我希望在不指定每个返回数组的情况下使用$result2的结果,以防表在某个时刻被编辑。可能的

您将获得作为关联数组和索引数组的结果。

要只获取关联数组,可以使用:

$result = $sth->fetchAll(PDO::FETCH_ASSOC);