Creating a PHP CMS – Part 4

This post is part of a series about creating a PHP CMS. Click here to start from the beginning.

Today we are going to be getting the page from the database and displaying it to the user. We will also set a home page for when a specific page is not requested.

If you haven't already, create a few pages using the form we created in Part 3, and check the pages table in your database viewer to make sure everything is working correctly.

After you've created a few pages, let's get into our database viewer to execute some SQL queries. In your pages table, choose one of your posts to use as a home page, and remember its id.

On your database, execute this query.

INSERT INTO settings (name, VALUE) VALUES ('homePage', 'id');

Be sure you replace id with the page ID you chose.

Now execute this query on the database.

INSERT INTO settings (name, VALUE) VALUES ('homeTitle', 'title');

Replace title with what you want to be displayed in the title bar on the home page. It should be something like the name of your site.

Displaying Information

Now that we've set information for the home page, we can get into some PHP.

We will start by creating some more functions in functions.php. Today we will be creating four new functions called title, pageTitle, pageBody and pageDate.

Title Bar

With our title function, we will be displaying the title bar text. We will be using $_GET today. $_GET is similar to $_POST, except with $_GET, the information is displayed in the URL. For example, in 'index.php?id=23', there would be a variable called $_GET['id'] with a value of 23.

Insert this code into the title function.

if ($_GET['id']) {
} else {
}

If an ID is specified, display the title of the page with that ID. If none is specified, then get the value of the homeTitle setting and display that.

Inside the if block, we will put the value of $_GET['id'] in a variable called $pageID. We will convert it to an integer because that was type that the id field in our table was.

$pageID = (int) $_GET['id'];

Now, we will use another mysql query using mysql_query. This time, we will be using it in a variable called $result. This is because we will be using it to create an array from the mysql query.

$result = mysql_query("SELECT title FROM pages WHERE id='$pageID'");

SELECT title FROM pages means that we will get the value of the 'title' field from the 'pages' database. WHERE id='$pageID' means that we will only select a row where the 'id' field has this value (In this case it's the value we put in $pageID).

$row = mysql_fetch_array($result);

This uses mysql_fetch_array to take our MySQL query and turn the result into an array, and then stick that array in $row.

echo $row['title'];

This just displays the value of the key called 'title'. The key is the same as the field we used in our MySQL query.

Inside the else section, insert this code.

$result = mysql_query("SELECT value FROM settings WHERE name='homeTitle'");
$row = mysql_fetch_array($result);
 
echo $row['value'];

This pretty much does the same thing as what we just did, except it uses the value that we set as the home page title on the settings table.

Page Title

Paste the code inside of the title function into the pageTitle function. Inside the else section, replace 'homeTitle' in the MySQL query with 'homePage', and delete the line containing

echo $row['value'];

and add in

$pageID = $row['value'];
 
$result = mysql_query("SELECT title FROM pages WHERE id='$pageID'");
$row = mysql_fetch_array($result);
 
echo $row['title'];

This code will first get the home page ID specified in the 'settings' table and use that ID to get a title from the 'pages' table.

Page Body and Page Date

In the pageBody function, paste in the content of the pageTitle function, replacing all instances of 'title' with 'body'. Do the same with pageDate, this time replacing 'title' with 'date'.

However, there is an extra step with pageDate. Delete the echo statements, and replace them with

$date = date('M d, Y', $row['date']);

Remember how we stored dates as Unix time? This converts it to a human-readable date and sticks it into a variable called $date. Now we can just echo $date to display the date the page was published.

Using These Functions

Now that we've created the functions, we can start using them in index.php. Open up index.php in your text editor, and add in a basic HTML page structure. At the top of the file, add a PHP block. Inside this PHP block, include functions.php and connect to the database.

Now add this between the title tags.

<?php title(); ?>

Now you can use <?php pageTitle(); ?>, <?php pageBody(); ?> and
<?php pageDate(); ?> to display the page.

Open index.php in your browser and, if everything went correctly, you should see the page you set as the home page. Try adding ?id=page (replace 'page' with the ID of one of your posts) to see a different page.

In the next post in this series, we will be displaying a list of posts, for a navigation list and for an administration panel.

Click here for Part 5

Stay Updated

Did you enjoy this post? Don't miss a single post by getting free updates!

31 Comments

  1. August 18, 2009

    I think you should remove the single quote before and after $pageID, because $pageID is a number not a string.
    Do you think so?

  2. August 18, 2009

    Hua Chen: You could remove the single quotes, but it still works perfectly fine either way. There could possibly be a small speed difference, but it probably wouldn't be noticeable.

  3. August 18, 2009

    You removed single quotes but also works fine because mysql or php makes a automactic change from string to number, so it may take a litter longer time with single quotes with number.

  4. September 3, 2009

    i'm confused, is this code suppose to be for the function.php page or for the database?, it doesn't seem to be working.

  5. September 3, 2009

    Duane: The code in the first two boxes are to be executed in your database manager. The rest should go into functions.php.

    Hope that helps.

  6. September 3, 2009

    Thanks, I keep getting errors though,

    'Parse error: syntax error, unexpected T_VARIABLE, expecting '(' in /home/paganc/public_html/Duane-Folder/functions.php on line 14'

    and using the code

    '//Title Bar

    if $homeTitleID = (int) $_GET['id'];
    else
    result = mysql_query("SELECT value FROM settings WHERE name='homeTitle'");
    $row = mysql_fetch_array($result);

    echo $row['value'];
    }'

    ?

  7. September 3, 2009

    Duane: Can you please tell me which line is line 14?

  8. September 3, 2009

    sorry to paste the lot but...

  9. September 3, 2009

    Oops, erm it didn't paste everything :(

    erm, if $homeTitleID = (int) $_GET['id']; is on line 14.

  10. September 3, 2009

    Duane: It looks like a syntax error. If you are comparing the values, '$homeTitleID = (int) $_GET['id']' needs to be wrapped in parentheses, and the '=' needs to be '==', because '=' is an assignment operator, and '==' is a comparison operator.

    You can check Part 7, because there is a link to download the entire project, and you can take a look at functions.php if you are not sure what to do.

  11. September 5, 2009

    ok, i've done that now, but for some reason its having problems connecting to the database

    $row = mysql_fetch_array($result); has an error :S

    Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/paganc/public_html/Duane-Folder/functions.php on line 23

    I used the script in the zip file. and get that error.

  12. September 5, 2009

    Duane: What is the value of $result? It looks like that variable is the problem. Or it could be a problem with the database.

    Also, try checking the database in config.php, and make sure everything is correct.

  13. September 5, 2009

    the value is correct its pretty much a copy and paste from your tutorial.

  14. September 5, 2009

    Duane: What about config.php? Make sure that your database user has proper permissions for the database.

  15. kt
    November 4, 2009

    after this section, there is no code. looks like a <pre> tag is not closed in your html? :
    Page Title

    Paste the code inside of the title function into the pageTitle function. Inside the else section, replace 'homeTitle' in the MySQL query with 'homePage', and delete the line containing

    echo $row['value'];

    and add in

    *** NOTHING HERE***

  16. November 4, 2009

    @kt: Thanks for pointing that out. I forgot a quote in the pre tag.

  17. January 17, 2010

    I'm sorry but this is confusing. After you say put this code in for the function title()

    you don' t say where to put anything else. You say put this in the if block- but what do you mean? i think what would help too, is that at the end of each lesson you show an overall of what our code should look like after that lesson. You are doing a great job, there is just a little confusion with some things, and I cannot move forward.

    • January 17, 2010

      I agree that this is a little bit confusing. I wrote this a long time ago as a reference for myself. And now I'm wondering "What was I thinking?" :)

      When I say put something in something else, I usually mean in between curly brackets { }

      Each line of code I show will generally go in the order in which they are shown. For example:

      function title() {
          if ($_GET['id']) {
              $pageID = (int) $_GET['id'];
       
              $result = mysql_query("SELECT title FROM pages WHERE id='$pageID'");
              $row = mysql_fetch_array($result);
       
              echo $row['title'];
          } else {
              $result = mysql_query("SELECT value FROM settings WHERE name='homeTitle'");
              $row = mysql_fetch_array($result);
       
              echo $row['value'];
          }
      }
  18. October 19, 2010

    I keep getting this error message
    Notice: Undefined index: id in C:\wamp\www\cms\index.php on line 22

    What could be the proble?

    • October 19, 2010

      "Undefined index" means that you are trying to access an element of an array that doesn't exist. In this case you're trying to access something like $arr['id'], which does not exist.

      What exactly do you have on line 22?

      • October 20, 2010

        I am actually learning using your codes. I download it and copied it verbatin just to get a grip.

        This is line 22

        -


        Not found

        • October 20, 2010

          Sorry it didn't come up here is line 22
          if (in_array($_GET['id'], $IDs) || !$_GET):

        • October 20, 2010

          It looks like $_GET['id'] doesn't exist. Try testing to see if it exists using isset($_GET['id']), and see if that helps.

  19. rognvaldr
    November 10, 2010

    Would it be better if the entries in the `settings table` be defined as constants in the config file instead?

    I find it cumbersome to e.g. make a database request just to get homepage id.

    But other than that, awesome tutorial. I have no problem with the coding. I just don't know how exactly CMS are put together.

    • November 15, 2010

      The main reason for using a database entry to store the home id, as opposed to using constants, is to allow you to easily change it via the admin panel, as you'll see in a later part of the tutorial series, which would be more difficult to do using constants.

      Also, I apologize for being late to approve comments, I haven't been receiving email notifications for some reason :/

  20. December 29, 2010

    Hi! I am getting an error message

    Notice: Undefined index: id in C:\wamp\www\cms\functions.php on line 36
    freetibet

    Notice: Undefined index: id in C:\wamp\www\cms\functions.php on line 60
    fdasfdafdfadsfdasfadsfdfdfadsfdasfadsfdfdfadsfdasfadsfdfdfadsfdasfadsfdfdfadsfdasfadsfdfdfadsfdasfadsfdfdfadsfdasfadsfdfdfadsfdasfadsfd

    Notice: Undefined index: id in C:\wamp\www\cms\functions.php on line 82
    Dec 22, 2010

    Line 19/36/60/82 in function.php is
    ..... if ($_GET['id'])
    Line

    Plzz can you please help with this...
    And in case, if I put ?id=2 at the end, it work fine...

    • December 29, 2010

      See my response to Louis' comment.

      tl;dr: Change if($_GET['id']) to if(isset($_GET['id'])) to check if the variable exists or not, rather than check if its value is true and potentially try to use a variable that may not exist.

      • January 18, 2012

        Dear this command is working fine
        if(isset($_GET['id']))
        thanks a lot

  21. ivan
    May 4, 2011

    Hello,

    Please send me a complete function.php files,or upload here.Somewhere I'm wrong because I do not understand the above description, but I do not know where.

    Thanks,

    Ivan

Trackbacks/Pingbacks