PHP Tutorial

Step 5

PHP Tutorial

In this tutorial we will create a simple twitter copycat. In step 5 we will create a new page that lists tweets from one user only.

Step 5

1. To create a new page we will start by creating the PHP file responsible for the business logic of that page. This page will be very similar to the list_all.php page we created before with two differences:

The template to use can be the same one we used for the list_all.php pages (code reuse FTW).

2. The new page will be called tweets/list_user.php and it will look like this:

  include_once($BASE_DIR .'database/tweets.php');

  $username = $_GET['username'];

  $tweets = getUserTweets($username);  

  $smarty->assign('tweets', $tweets);

3. We should always verify if the input parameters are correct. For now we will just exit with an error if the //username// doesn’t exist in the $_GET array. Later we will do some better error handling. Add this to the top of your page.

  if (!isset($_GET['username'])) die('username missing');

4. We now have to create the new function in the database/tweets.php file:

  function getUserTweets($username) {
    global $conn;
    $stmt = $conn->prepare('SELECT *
                            FROM tweets JOIN
                                 users USING(username)
                            WHERE username = ?
                            ORDER BY time DESC');
    return $stmt->fetchAll();

While we were at it we also made our queries more pleasant to the eye.

5. Now, in our tweets/list.tpl template we just have to make sure that clicking an username will get us to this page. Change this line:

    <a href="#" class="username">@{$tweet.username}</a>

to this:

    <a href="{$BASE_URL}pages/tweets/list_user.php?username={$tweet.username}" class="username">@{$tweet.username}</a>

6. We still need a way to return to our initial page and every page should have an header with a link to the beginning. So lets create a header in our common/header.tpl template:

<!DOCTYPE html>
    <meta charset='utf-8'>
    <link rel="stylesheet" href="{$BASE_URL}/css/style.css">
      <h1><a href="{$BASE_URL}">Fritter</a></h1>

We needed a name, I decided to call ou site Fritter:


    1. waste time, money, or energy on trifling matters.
    "I wish we hadn't frittered the money away so easily"
    synonyms: squander, waste, misuse, misspend, spend unwisely, throw away, dissipate, make poor use of;

It seemed appropriate…

In step 6 we will create a form for user registration.