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

require_once doesn't work

In "Using PHP with MySQL" -> "Limiting Records in SQL Queries" -> "Using Limit with Offset", I have a very strange problem.

The teacher's code in function get_products_subset($positionStart, $positionEnd) is

$offset = $positionStart - 1;
$rows = $positionEnd - $positionStart + 1;

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

try {
    $results = $db->prepare("SELECT name, price, img, sku, paypal
        FROM products ORDER BY sku LIMIT ?, ?");


    $results->bindParam(1, $offset, PDO::PARAM_INT);
    $results->bindParam(2, $rows, PDO::PARAM_INT);
    $results->execute();
} catch (Exception $e) {
    echo "Data could not be retrieved from database.";
    exit;
}

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

That's fine, but if i change the require statement to require_once, the code stop working. It says "Notice: Undefined variable: db in..." while variable db is defined in database.php. Anyone has some idea?

2 Answers

Hi Sen,

Changing require to require_once shouldn't change the behaviour of your $db variable, could you please post the code from your database.php file minus your auth credentials so we can check it for errors.

Sure, here's the database.php code: <?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;
    }

    ?>

DB_HOST is "localhost", DB_NAME is "shirts4mike", DB_PORT is "3306" and DB_USER is "root".

I'm really confused about the code markdown format...