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

my 'add_project($title, $category)' function returns NULL in if test

Hi, I am having some issues with my code. In this video Alena asks us to test our 'add_project()' function (with parameters) stating that is all is good it should return true or false if the database connection works. However when i var_dump the function with parameters it returns NULL. Not sure what is wrong here.

Video in question: CRUD Operations with PHP -> Adding projects

add_project() function

function add_project($title, $category) {
    include 'connection.php';

    $sql = 'INSERT INTO projects(title, category) VALUES (?, ?)';

    try {
        $results = $db->prepare($sql);
        $results->bindValue(1, $title, PDO::PARAM_STR);
        $results->bindValue(2, $category, PDO::PARAM_STR);
        $results->execute();
    } catch ( Exception $error ) {
        echo "Error!: " . $error->getMessage() . "<br />";
        return false;
    }
}

project_list.php code

if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
    $title = trim(filter_input(INPUT_POST, 'title', FILTER_SANITIZE_STRING));   
    $category = trim(filter_input(INPUT_POST, 'category', FILTER_SANITIZE_STRING)); 

    if ( empty($title) || empty($category) ) {
        $error_message = 'Please fill in the required fields: Title, Category';
    } else {
        var_dump(add_project($title, $category));
        if ( add_project($title, $category) ) {
            header('Location: /crud-task-app/project_list.php');
            exit;
        } else {
            $error_message = 'Could not add project';
            echo 'the project is added, but not redirect';
        }
    }
}

Odd but if i add a "return true;" at the end of my TRY block in the add_project() function. It appears to work as intended and redirects correctly.

adding "return $results->execute();" appears work as well, but the lesson led me to believe this was not required.

1 Answer

At approximately 4:18 in the video i noticed Alena adding a "return true;" statment at the end of the "add_project()" function. My bad, should have paid more attention.