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;

}
Mikis Woodwinter
Mikis Woodwinter
44,925 Points

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.