Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Development Tools Using PHP with MySQL Querying the Database with PHP Avoiding Duplication

17,532 Points

Why is Randy using require instead of require_once?

So far, Randy had always used "require_once" to include php files that have objects or functions. In this case, he uses "require" to include the code that creates the PDO object to connect to the database.

This is the code to create the object (database.php):

try {

    $db = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME .";port=" . DB_PORT,DB_USER,DB_PASS);


    $db->exec("SET NAMES 'utf8'");

} catch (Exception $e) {
    echo "Could not connect to the database.";

This is the code that is requiring the previous code:

function get_products_all() {
         require(ROOT_PATH . "inc/database.php");

        $results = $db->query("SELECT name, price, img, sku, paypal FROM products ORDER BY sku ASC");

    } catch (Exception $e) {

        echo "Data could not be retrieved from the database.";

    $products = $results->fetchAll(PDO::FETCH_ASSOC);    

    return $products;


I have the same question ... The PHP documentation has this to say about the distinction between the two:

"The require_once statement is identical to require except PHP will check if the file has already been included, and if so, not include (require) it again.

...maybe it has something to do with needing to let the database object get instantiated every time??? I don't know but I really want to know.