This course will be retired on June 1, 2025.
Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
We've successfully moved our media catalog into a database. All the pages are now working as they did before. However, we have a couple places where our queries are not as efficient as they could be. We have a number of functions that are taking the full catalog array before using PHP to narrow down the items to a smaller list.
functions.php
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 retrieved results";
exit;
}
$catalog = $results->fetchAll();
return $catalog;
}
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;
}
index.php
$random = random_catalog_array();
foreach ($random as $item) {
echo get_item_html($item);
}
RANDOM Functions in Popular Databases
SQLite | RANDOM() |
---|---|
MySQL | RAND() |
PostgreSQL | RANDOM() |
SQL Server | RAND() |
Oracle | DBMS_RANDOM.RANDOM |
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up