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.
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.
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
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.
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
Kabarovsky: That's odd. Try changing mysql_real_escape_string to addslashes and see what happens.
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...
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! ^_^
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!
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.
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?
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.
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!
The quotes are really mostly extra protection, just in case... :P
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.
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?
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.
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
<?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?
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?
To clarify, it's a parse error, not an arse error :-S