简体   繁体   中英

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

When using PDO to fetch values from a mysql database I get some redundant information, and I'm wondering why. The php function below returns the values as I want them to be returned. But if I return my result array, I get double values.

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 returns:

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

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

)

$Result2 returns:

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

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

)

Why is $result acting like this? Its like its fetching my data multiple times. Am I using the code wrong? If possible, I want to use the result of $result2 without specifying each return array - in case the table is getting edited at some point. Possible?

You are getting the results both as an associative array and an indexed array.

To get only the associative array, you can use:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM