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

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

SERGIO RODRIGUEZ
SERGIO RODRIGUEZ
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->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);

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

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

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.";
        exit;
    }

    $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.