Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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,709 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:

<?php 
    try{
        $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,709 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.