0

I've been at this for some time. Using PDO's documentation and based on older stackoverflow posts I feel I am doing this correct, however I can not figure out where my data is in the array returned by fetchAll. Any help would be appreciated.

In my DatabaseHandler class:

public function getStateList(){
    $root = "root";
    $rootpasswd = "password";
    $host = "localhost";
    try{
        $dbh = new PDO("mysql:host=$host;dbname=TESTDATA;", $root, $rootpasswd);
        $stmt = $dbh->prepare("SELECT id FROM state");
        if(!$stmt->execute()){
            //error
        }
        $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
        return $result;
    }catch(PDOExeption $e){
        //catch exception
    }
}

Now when calling this method it returns an array of 52 id's which is what it's supposed to do however I can not get to this data. Why? Here is the code that calls the method.

<?php
    require("./Database/DatabaseHandler.php");

    $dbh = new DatabaseHandler();
    $stateCodes = $dbh->getStateList();
    $max = sizeof($stateCodes);

    error_log("Arraysize=".$max."\n", 3, "/testlog/data.dat");
    error_log("Position 0: ".$stateCodes[0]."\n", 3, "/testlog/data.dat");
    error_log("Position[0][0]: ".$stateCodes[0][0]."\n", 3, "/testlog/data.dat");
    error_log("Position[0][0][0]: ".$stateCodes[0][0][0]."\n", 3, "/testlog/data.dat");
?>

The first errorlog records 52. The second returns the word Array which makes me think it's a 2 dim array. The Third nothing. The Fourth Nothing.

I know I am using fetchAll wrong somehow but I can't figure out where or how. Thank you in advance.

4

1 回答 1

0

您已经使用PDO::FETCH_ASSOC了关联数组。

但是由于您要获取所有内容,因此该数组是二维的。

$stateCodes[0]['id'];

或者,您可以这样循环:

foreach($stateCodes as $code){
    error_log("Code Id =" . $code['id']);
}
于 2014-09-24T16:13:33.350 回答