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 CRUD Operations with PHP Creating Records Reading Project Data

Error in functions.php: Undefined Variable $db - Alena PHP CRUD Tutorial

Hi. I am making Alena PHP CRUD tutorial but when i put this code in my functions.php (inside inc folder) i receive this error:

Undefined Variable $db

I am using correctly the include connection.php so... what is the problem?

This is my connection.php

<?php

try {
    $db = new PDO("sqlite:".__DIR__."/database.db");
    $db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
} catch (Exception $e) {
    echo $e->getMessage();
    exit;
}
var_dump($db);

And this is my functions.php:

<?php
//application functions

function get_project_list() {
    include 'connection.php';

    try {
        return $db->query('SELECT project_id, title, category FROM projects');
    } catch (Exception $e) {
        echo "Error!: " . $e->getMessage() . "</br>";
        return array();
    }
}
Qasim Hafeez
Qasim Hafeez
12,731 Points

You're not calling the function. You have to call it like:

get_project_list();

In the function you can put the results of the query into a variable and then var_dump the variable.