2. database_queries.php
• Contains many php functions which query the
database for information.
• This data is sometimes “returned” with return
to where the function was called
• Other times, this data is simply echoed from
database_queries.php
CGS2835 WebDev
4. Get data for a user
• We can ask the database columns of
information for a particular userID
5. database_get_username($userID)
===== In MODEL database_queries.php =====
function database_get_username($userID)
{
$userID = sanitize_input($userID);
$data = mysql_query("SELECT username FROM users WHERE userID='$userID'");
$row = mysql_fetch_array($data);
$result = $row['username'];
return $result;
}
===== “Calling” the function, printing the data on the VIEW (user.php) =====
$username = database_get_username($userID);
echo $username;
CGS2835 WebDev
6. Insert posts for a user
• The VIEW user.php has a form that displays if
$userID is the same as the $loggedInUser
• This form collects a post and sends it to the
controller post_process.php
7. Calling database_add_user_post($userID, $message)
== In post_process.php (Controller, processing the data)==
// Get the message to post
$post = $_POST["post"];
// Get the user logged in
$userID = get_user_logged_in();
// Insert the new post into the database for that user
// call the database_add_user_post function and provide the variables
// $userID and $post
database_add_user_post($userID, $post);
// Go back to the user's page
header('Location: user.php?userID=' . $userID);
CGS2835 WebDev
8. database_add_user_post($userID, $message)
== In database_queries.php (Model inserting the data) ==
function database_add_user_post($userID, $message) {
// Sanitize the variables $userID and $message
$userID = sanitize_input($userID);
$message = sanitize_input($message);
// Insert the data (userID, message) into the posts table
$q = "INSERT INTO posts (userID, message) VALUES ('$userID',
'$message')";
mysql_query($q);
}
CGS2835 WebDev
9. Select posts for a user
• With post data inserted for a user, we can
select the post data out to display it.
• This will require a VIEW (echo data) and
MODEL (select data)
11. database_get_user_posts($userID)
===== In database_queries.php =====
// Get all of the posts for a userID
function database_get_user_posts($userID)
{
$userID = sanitize_input($userID);
$posts = "";
$q = "SELECT message,timestamp FROM posts WHERE userID='$userID' ORDER BY
timestamp DESC";
$result = mysql_query($q);
while($row = mysql_fetch_array($result))
{
$message = stripslashes($row['message']);
$timestamp = $row['timestamp'];
$posts = $posts . $timestamp . ": " . $message . "<br />";
}
return $posts;
}
12. Many more queries
• There are many more interactions in the
database in database_queries.php
• Later topics:
– password hashing, database security.
– Designing the layout
– Adding functionality