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

Something went wrong. Its not even giving me an error message that it can't connect to the database

code for config.php

define("BASE_URL","/");
    define("ROOT_PATH",$_SERVER["DOCUMENT_ROOT"] . "/");

    define("DB_HOST","localhost");
    define("DB_NAME","shirts4mike");
    define("DB_PORT","8889");
    define("DB_USER","root");
    define("DB_PASS", "root");

code i added for products php

require(ROOT_PATH . "inc/database.php");

    try{
        $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));

code for 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::ERROMODE_EXCEPTION);
    $db->exec("SET NAMES 'utf8'");
} catch (Exception $e) {
    echo "Could not connect to the database.";
    exit;
}

after inspecting the element and checking for errors google said this "Failed to load resource: the server responded with a status of 500 (Internal Server Error) " I get that response on every page but database.php where it says i can't connect to the server

2 Answers

Chris Shaw
Chris Shaw
26,636 Points

Hi Trisha,

Sorry for the delay, I'm still trying to catch up on other forum threads, the only code I can see that would cause an issue such as this is your require statement in your products.php file for **database.php`, try changing it to the below which should show whether or no your file path is incorrect.

<?php

try {
    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;
}
Luis Palma
Luis Palma
7,869 Points

In the products.php the code that you added : $products = ($results->fetchAll(PDO::FETCH_ASSOC));

The correct code is : $products = $results->fetchAll(PDO::FETCH_ASSOC);