PHP Using PHP with MySQL Querying the Database with PHP Retrieving the Result Set

Why is after the fetchAll function, it retreives the one numeric key one associative key?

I just want to know the basic idea of this fetchAll, why after the this function it cant just normally retrive the original key?

2 Answers

Andrew Shook
Andrew Shook
31,707 Points

NIcholas, PDO by default retrieves information from the database in an array that contains both associative and numeric indexes. If you would like one or the other you can set that value using PDO::setFetchMode() method. After you make a new PDO object, you can use this method to tell PDO to return results in a numeric array, associative array, as an object, or as a class. For more information, check out the PHP manual here. Here is a quick example:

        $database = new PDO("mysql:host=$host;port=$port;dbname=$db;user=$user;password=$pass");
        $database->setFetchMode(PDO::FETCH_ASSOC); //Could also be FETCH_NUM, FETCH_OBJ, or FETCH_CLASS
    }catch (Exception $e){
         echo "Unable to connect: " . $e->getMessage() ."<p>";

Thank you very much, I think I was not paying enough attention to this tutorial, thank you for answering my question. And the key idea in this video, I believe is when you have questions about php, go php manual and check it yourself. Thx a lot. I will make good use of PHP manual from now on.

Andrew Shook
Andrew Shook
31,707 Points

The PHP manual is always a good resource to use, but somethings the documentation is a little difficult to understand. Always feel free to ask a question here on treehouse or try a quick google search. Best of Luck.