Creating a PHP CMS – Part 3

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

Today, we will be using a form to get information and add it to the database.

Creating a Form

First, to get the information, we need to create a form. Our form will be in the new.php file.

Paste the contents of new.txt into new.php. Update: Sorry, I do not seem to have this file anymore, but if you have a basic knowledge of HTML it should be fairly simple to piece together.

The action attribute of form tells us which page the user will go to when they click the submit button. The method attribute tells us how it is sent to the server. The value 'post' means that the information sent will not be shown in the URL. Another method is get, where the information is displayed in the URL. We will be using get later.

Form Validation

After the user submits the form, something has to be done with the information they sent. We will be using a variable called $_POST.

For example, if a user submits a form, and in that form there is a field called 'userInput', and they entered 'hello, world', $_POST['userInput'] would contain 'hello, world'.

In create.php, insert your PHP start tag and include functions.php. You will need to include it as '../functions.php' because create.php is in the admin directory. '../' means the parent directory.

First, we will establish a database connection using connect();. And then we will check that the form fields are filled in, using an if statement.

if ($_POST['title']) {
}

This checks if $_POST['title'] is true. If the 'title' field wasn't filled in, $_POST['title'] would be an empty string, meaning that it is false.

If the title is entered, we will store it in a variable called $title. However, we aren't just going to use

$title = $_GET['title'];

Instead, we will use mysql_real_escape_string. This 'escapes' potentially harmful characters by adding a backslash in front of them so that the form input doesn't cause any problems. We will be using this with all user input.

if ($_POST['title']) {
    $title = mysql_real_escape_string($_POST['title']);
}

We still need to do something if $_POST['title'] is not true, by using else. We will show an error message telling them to fill in the title field.

You should have something like this now.

// Check if the title is entered
if ($_POST['title']) {
    $title = mysql_real_escape_string($_POST['title']);
} else {
    echo '<p>The title field is empty.</p>';
}

Now we can do the same thing with the body text.

// Check if the body is entered
if ($_POST['body']) {
    $body = mysql_real_escape_string($_POST['body']);
} else {
    echo '<p>The body field is empty.</p>';
}

We can get the date using time.

$date = time();

Now, before we insert values into the database, we will check that the title and body fields are filled by using an if statement with the && operator. && means 'and', so the expression for the if statement will only be true if both values are true.

if ($title && $body) {
}

The method that we will use to execute MySQL queries is with mysql_query. There are other methods to execute queries, but I won't discuss them in this series.

mysql_query("INSERT INTO pages (title, body, date) VALUES ('$title', '$body', '$date')");

Let's take a look at the SQL query. INSERT INTO pages means that we will be adding a row to a table called pages. (title, body, date) means that we will be working with the fields title, body and date. VALUES ('$title', '$body', '$date') means that the values we are inserting will be using these variables. The values you are inserting must be in the same order as the list of fields to work with.

You may notice that I used double quotes here, but in all of the other strings I used single quotes. This is because with double quotes, variables can be placed in strings, but they cannot with single quotes. Also, I prefer to use single quotes in SQL queries.

After the if statement, we will use else to show a link back to new.php if either of the fields is not filled.

// If the title and body are both entered, insert into the database
if ($title && $body) {
    connect();
 
    mysql_query("INSERT INTO pages (title, body, date) VALUES ('$title', '$body', '$date')");
} else {
    echo '<p><a href="new.php">Back</a></p>';
}

Now to test that everything is working correctly, point your browser to admin/new.php and enter some test information. If everything works fine, you should see a blank page. If you got an error message, check your code to see if you made any mistakes. Areas to check would be functions.php, new.php and create.php.

If you get a blank page, check your database viewer to see if any new rows have been added. If you see a new row, then you're done with this part of the series!

If you have any questions, be sure to leave a comment.

Click here for Part 4

Stay Updated

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

27 Comments

  1. August 14, 2009

    I have some problems...

    This is my create.php file :
    http://postavi.com/images/create.gif

    But when I put something in new.php and click publish I got these erorrs:
    http://postavi.com/images/erorr.gif

    • August 14, 2009

      Kabarovsky: It seems that there is a problem with your MySQL database, or with mysql_real_escape_string. However, on my server at least, mysql_real_escape_string works before the database connection is established. Try moving connect(); to the line right after including functions.php, and let me know what happens.

      Also, what version of PHP are you using? This could have something to do your PHP version.

  2. August 15, 2009

    Hi... First I was remove connect(); right after including functions.php and after that link "back" was there.. but i look in phpmyadmin and table "pages" is empty

  3. August 15, 2009

    Kabarovsky: That's odd. Try changing mysql_real_escape_string to addslashes and see what happens.

  4. August 16, 2009

    Same.. I click on publish button and after that create.php file is open, link back is there but in phpmyadmin table is empty again...

  5. August 18, 2009

    Very well using mysql_real_escape_string, it is very important!
    But you miss a small thing, you forget to set the default timezone when using time() function.
    If you know Chinese, you can have a look at my blog post: http://blog.huachen.me/php-beijing-time, but if you don't know Chinese, you can also search the php function date_default_timezone_set() for answer! ^_^

  6. August 18, 2009

    A question for you:
    Why you add the single quotes in the SQL query string: mysql_query("INSERT INTO pages (title, body, date) VALUES ('$title', '$body', '$date')"); ?
    If you delete these single quotes, it will also work well.
    Can you tell me why? Thanks!

  7. August 18, 2009

    Kabarovsky: This may have something to do with your database configuration. I don't have access to your DB, so I'm not sure what the problem could be.

    Hua Chen: I guess it's just what I'm used to, like how I always use quotes around the values of HTML attributes.

  8. August 18, 2009

    I have compared the speed of these two, the one with single quotes took double the time to the one without single quotes. I also write a blog post about that:http://blog.huachen.me/php-sql-quote-string . But I just don't know why should always add that?

  9. August 18, 2009

    Hua Chen: There are some speed differences. I think that the quotes may also help to prevent SQL injection, but I'm not completely sure.

  10. August 18, 2009

    I also afraid of SQL injection, but didn't mysql_real_escape_string has already prevent it? Can you help me Google it in Google English or ask your friends about it? Thanks!

  11. August 18, 2009

    The quotes are really mostly extra protection, just in case... :P

  12. August 19, 2009

    Kabarovsky: This is probably not the case, but you can try making sure that the value of the 'name' attributes in your form fields match your $_POST values.

  13. August 27, 2010

    I have tried this code, initially i got errors refering to "mysql_real_escape_string"

    I decideed to remove this and just use "$title = $_GET['title'];".

    I now hav enoerrors but the data is not saving, Am I doin fsomething wrong?

    • August 27, 2010

      If you're getting errors with mysql_real_escape_string, that probably means that there is a problem with your connection to the MySQL database.

      Remember: When inserting data into a database using these methods it is always crucial to sanitize your inputs using mysql_real_escape_string, doing otherwise would be a huge security risk (See the SQL injection section of Hack Your Own Site. That article also mentions using prepared statements, a "newer" way of doing this, which is not mentioned in this article.

  14. Kars
    September 26, 2010

    Ah man all the time it was giving empty fields and i didn't know why! But i had deleted connect() at the start because i thought it wasn't needed since it was already called to later on with the insert query. I had to find out that mysql_real_escape_string does only work when there 's a connection with the database >.<. Kinda logic, but it's nice to know. Moving on..;p

  15. DavE
    March 3, 2011

    <?php
    include '../functions.php'
    connect();

    // Check if the title is entered
    if ($_POST['title']) {
    $title = mysql_real_escape_string($_POST['title']);
    } else {
    echo 'The title field is empty.';
    }

    // Check if the body is entered
    if ($_POST['body']) {
    $body = mysql_real_escape_string($_POST['body']);
    } else {
    echo 'The body field is empty.';
    }

    $date = time();

    // If the title and body are both entered, insert into the database
    if ($title && $body) {
    connect();

    mysql_query("INSERT INTO pages (title, body, date) VALUES ('$title', '$body', '$date')");
    } else {
    echo 'Back';
    }
    ?>

    what is wrong?

  16. lizzie
    April 12, 2011

    Hii thanks for the wonderful tutorial. I'm up to the end of this page and I'm having trouble with functions.php, I get the following error

    {arse error: syntax error, unexpected T_REQUIRE_ONCE on line 4

    It's
    require_once '../functions.php';
    on line 4.

    Any suggestions?

    • lizzie
      April 13, 2011

      To clarify, it's a parse error, not an arse error :-S

  17. shreekant
    July 26, 2011

    my directory structure is as follows:
    Is this currect
    SCMS-aplication(files)-admin-(files)

  18. prince
    September 20, 2011

    wow!its working.thank you very much for your helpful tutorial :-)

  19. Gautam
    November 25, 2011

    Hi,
    Ok I reached this stage, but I'm getting these errors:

    Deprecated: Assigning the return value of new by reference is deprecated in C:\xampp\php\PEAR\Config.php on line 80

    Deprecated: Assigning the return value of new by reference is deprecated in C:\xampp\php\PEAR\Config.php on line 166

    Notice: Use of undefined constant DB_HOST - assumed 'DB_HOST' in C:\xampp\htdocs\Nexodus\functions.php on line 7

    Notice: Use of undefined constant DB_USER - assumed 'DB_USER' in C:\xampp\htdocs\Nexodus\functions.php on line 7

    Notice: Use of undefined constant DB_PASS - assumed 'DB_PASS' in C:\xampp\htdocs\Nexodus\functions.php on line 7

    Warning: mysql_connect() [function.mysql-connect]: php_network_getaddresses: getaddrinfo failed: No such host is known. in C:\xampp\htdocs\Nexodus\functions.php on line 7

    Warning: mysql_connect() [function.mysql-connect]: [2002] php_network_getaddresses: getaddrinfo failed: No such host is known. (trying to connect via tcp://DB_HOST:3306) in C:\xampp\htdocs\Nexodus\functions.php on line 7

    Warning: mysql_connect() [function.mysql-connect]: php_network_getaddresses: getaddrinfo failed: No such host is known. in C:\xampp\htdocs\Nexodus\functions.php on line 7
    Could not connect to database

    Why can't it recognise the config.php file?

    • Gautam
      November 26, 2011

      Ok I worked it out... just had to change the config.php file's name... i guess it was confusing config.php from the PEAR folder....

  20. henry
    January 9, 2012

    Hi Eric,

    I am following your post and the file new.txt is not available anymore. Could you send it to me? or tell me the codes to input?

    Thank you

  21. Russell
    February 16, 2012

    I too would like the new.txt file, could someone please fix it?

    thank you

Trackbacks/Pingbacks