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 Integrating PHP with Databases Filtering Input for Queries Combining Search and Pagination

Antonio English
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Antonio English
Front End Web Development Techdegree Graduate 18,103 Points

can someone please post their catalog.php, functions.php and suggest.php

can someone please post their catalog.php, functions.php and suggest.php. I want to compare it with what I have.

3 Answers

Sergey Podgornyy
Sergey Podgornyy
20,660 Points

You can download them directly from video lesson. You just need to press on tab "Downloads" and then on Project Files

Dario Preglej
Dario Preglej
9,771 Points

CATALOG

<?php include("inc/functions.php");

$pageTitle = "Full Catalog"; $section = null; $search = null; $items_per_page = 8;

if (isset($_GET["cat"])) { if ($_GET["cat"] == "books") { $pageTitle = "Books"; $section = "books"; } else if ($_GET["cat"] == "movies") { $pageTitle = "Movies"; $section = "movies"; } else if ($_GET["cat"] == "music") { $pageTitle = "Music"; $section = "music"; } }

if(isset($_GET["s"])){ $search = filter_input(INPUT_GET,"s",FILTER_SANITIZE_STRING); }

if(isset($_GET["pg"])){ $current_page = filter_input(INPUT_GET,"pg",FILTER_SANITIZE_NUMBER_INT); }

if(empty($current_page)){ $current_page = 1; }

$total_items = get_catalog_count($section, $search); $total_pages = 1; $offset = 0; if ($total_items > 0) { $total_pages = ceil($total_items / $items_per_page);

//limit results in redirect $limit_results = ""; if(!empty($search)){ $limit_results = "s=".urlencode(htmlspecialchars($search))."&"; } else if(!empty($section)){ $limit_results = "cat=" .$section. "&"; }

//redirect too-large page numbers to the last page if($current_page > $total_pages){ header("location:catalog.php?" .$limit_results. "pg=".$total_pages); exit; }

//redirect too-small page numbers to the first page if ($current_page < 1){ header("location:catalog.php?" .$limit_results. "pg=1"); exit; }

//determine the offset (number of items to skip) for the current page //for example: on page 3 with 3 item per page, the offset would be 16

$offset = ($current_page - 1) * $items_per_page;

$pagination = "<div class=\"pagination\">";
$pagination .= "Pages: ";
for($i=1;$i<=$total_pages;$i++){
    if($i == $current_page){
        $pagination .= " <span>$i</span>";
    } else {
        $pagination .= " <a href='catalog.php?";
        if(!empty($search)){
            $pagination .= "s=".urlencode(htmlspecialchars($search))."&";
        }   else if(!empty($section)){
            $pagination .= "cat=".$section."&";
        }
        $pagination .= "pg=$i'>$i</a>";
    }
}
$pagination .= "</div>";

}

if(!empty($search)){ $catalog = search_catalog_array($search, $items_per_page, $offset);
} elseif(empty($section)){ $catalog = full_catalog_array($items_per_page, $offset); } else { $catalog = category_catalog_array($section, $items_per_page, $offset); }

include("inc/header.php"); ?>

<div class="section catalog page">

<div class="wrapper">

    <h1><?php 
    if ($search != null) {
        echo "Search Results for \"".htmlspecialchars($search)."\"";
    } else { 
    if ($section != null) {
        echo "<a href='catalog.php'>Full Catalog</a> &gt; ";
    }
    echo $pageTitle; 
    }?></h1>
    <?php 
    if($total_items < 1) {
        echo "<p>No items were found matching that search term.</p>";
        echo "<p>Search Again or "
            ."<a href=\"catalog.php\">Browse the Full Catalog</a></p>";
    } else {
        echo $pagination; ?>
    <ul class="items">
        <?php
        foreach ($catalog as $item) {
            echo get_item_html($item);
        }
        ?>
    </ul>
    <?php echo $pagination; 
    }?>
</div>

</div>

<?php include("inc/footer.php"); ?>

Dario Preglej
Dario Preglej
9,771 Points

FUNCTIONS

<?php

function get_catalog_count($category=null, $search=null){ $category = strtolower($category); include("connection.php"); try{ $sql = "SELECT COUNT(media_id) FROM Media "; if(!empty($search)) { $result = $db->prepare( $sql. " WHERE title LIKE ?"); $result->bindValue(1, "%".$search."%", PDO::PARAM_STR);
} elseif (!empty($category)){ $result = $db->prepare( $sql. " WHERE LOWER(category)= ? "); $result->bindParam(1,$category,PDO::PARAM_STR); } else { $result = $db->prepare($sql); } $result->execute(); } catch (Exception $e) { echo "bad query"; } $count = $result->fetchColumn(0); return $count; }

function full_catalog_array($limit = null, $offset = 0){ include("connection.php");

try{
    $sql=
        "SELECT media_id, title, category, img FROM Media 
        ORDER BY 
            REPLACE(
                REPLACE(
                    REPLACE(title, 'The ', ''),
                    'An ', 
                    ''),
                'A ', 
                ''
        )";
    if(is_integer($limit)) {
        $results = $db->prepare($sql. " LIMIT ? OFFSET ?");
        $results->bindParam(1,$limit,PDO::PARAM_INT);
        $results->bindParam(2,$offset,PDO::PARAM_INT);
    } else {
        $results = $db->prepare($sql);
    }
    $results->execute();

} catch (Exception $e) { echo "Unable to retrive results"; exit; } $catalog = $results->fetchAll(); return $catalog; }

function category_catalog_array($category, $limit = null, $offset = 0){ include("connection.php"); $category=strtolower($category); try{ $sql= "SELECT media_id, title, category, img FROM Media WHERE LOWER(category) = ? ORDER BY REPLACE( REPLACE( REPLACE(title, 'The ', ''), 'An ', ''), 'A ', '' )"; if(is_integer($limit)) { $results = $db->prepare($sql. " LIMIT ? OFFSET ?"); $results->bindParam(1,$category,PDO::PARAM_STR); $results->bindParam(2,$limit,PDO::PARAM_INT); $results->bindParam(3,$offset,PDO::PARAM_INT); } else { $results = $db->prepare($sql); $results->bindParam(1,$category,PDO::PARAM_STR); } $results->execute(); } catch (Exception $e) { echo "Unable to retrive results"; exit; } $catalog = $results->fetchAll(); return $catalog; }

function search_catalog_array($search, $limit = null, $offset = 0){ include("connection.php"); try{ $sql= "SELECT media_id, title, category, img FROM Media WHERE title LIKE ? ORDER BY REPLACE( REPLACE( REPLACE(title, 'The ', ''), 'An ', ''), 'A ', '' )"; if(is_integer($limit)) { $results = $db->prepare($sql. " LIMIT ? OFFSET ?"); $results->bindValue(1,"%".$search."%",PDO::PARAM_STR); $results->bindParam(2,$limit,PDO::PARAM_INT); $results->bindParam(3,$offset,PDO::PARAM_INT); } else { $results = $db->prepare($sql); $results->bindValue(1,"%".$search."%",PDO::PARAM_STR); } $results->execute(); } catch (Exception $e) { echo "Unable to retrive results"; exit; } $catalog = $results->fetchAll(); return $catalog; }

function random_catalog_array(){ include("connection.php");

try{
$results = $db->query(
    "SELECT media_id, title, category, img 
    FROM Media
    ORDER BY RANDOM()
    LIMIT 4");

} catch (Exception $e) { echo "Unable to retrive results"; exit; } $catalog = $results->fetchAll(); return $catalog; }

function single_item_array($id){ include("connection.php");

try{
$results = $db->prepare(
    "SELECT Media.media_id, title, category, img, format, year, genre, publisher, isbn 
    FROM Media
    JOIN Genres ON Media.genre_id = Genres.genre_id
    LEFT OUTER JOIN Books ON Media.media_id = Books.media_id
    WHERE Media.media_id = ?");
$results->bindParam(1, $id, PDO::PARAM_INT);
$results->execute();
} catch (Exception $e) {
echo "Unable to retrive results";
exit;
}
$item = $results->fetch();
if(empty($item)) return $item;
try{
$results = $db->prepare(
    "SELECT fullname, role
    FROM Media_People
    JOIN People ON Media_People.people_id = People.people_id
    WHERE Media_People.media_id = ?");
$results->bindParam(1, $id, PDO::PARAM_INT);
$results->execute();
} catch (Exception $e) {
echo "Unable to retrive results";
exit;
}
while($row = $results->fetch(PDO::FETCH_ASSOC)){
    $item[$row["role"]][]=$row["fullname"];
}
return $item;

}

function genre_array($category = null){ $category = strtolower($category); include("connection.php");

try{
    $sql = "SELECT genre, category"
        . " FROM Genres "
        . " JOIN Genre_Categories "
        . " ON Genres.genre_id=Genre_Categories.genre_id ";
    if (!empty($category)){
    $results = $db->prepare($sql 
        . " WHERE LOWER(category) = ?"                    
        . " ORDER BY genre");
    $results->bindParam(1,$category,PDO::PARAM_STR);
    } else {
    $results = $db->prepare($sql . " ORDER BY genre");
    }
$results->execute();
} catch (Exception $e) {
    echo "bad query genre";
}
$genres = array();
while ($row = $results->fetch(PDO::FETCH_ASSOC)){
    $genres[$row["category"]][]= $row["genre"];
}
return $genres;

}

function get_item_html($item) { $output = "<li><a href='details.php?id=" . $item["media_id"] . "'><img src='" . $item["img"] . "' alt='" . $item["title"] . "' />" . "<p>View Details</p>" . "</a></li>"; return $output; }

function array_category($catalog,$category) { $output = array();

foreach ($catalog as $id => $item) {
    if ($category == null OR strtolower($category) == strtolower($item["category"])) {
        $sort = $item["title"];
        $sort = ltrim($sort,"The ");
        $sort = ltrim($sort,"A ");
        $sort = ltrim($sort,"An ");
        $output[$id] = $sort;            
    }
}

asort($output);
return array_keys($output);

}