Dynamic website part 3 – inserting data into a database

by krike in General on 27 Feb 2011


This entry is part 3 of 3 in the series Dynamic web tutorials

The article form

let’s create a new file in our project named addarticle.php

We’ll start by adding a form. We need a field for the title, article content, a thumbnail and of course we need a submit button

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data">
	<p class="inputblock">
		<label for="title">Title</label><br />
		<input type="text" name="title" id="title" />
	</p>
	<p class="inputblock">
		<label for="thumbnail">Thumbnail</label><br />
		<input type="file" name="thumbnail" id="thumbnail" />
	</p>
	<p class="inputblock">
		<label for="content">Article content</label><br />
		<textarea cols="80" rows="12" name="content" id="content"></textarea>
	</p>
	<p class="submitblock">
		<input type="submit" name="submit" id="submit" value="Add new article" />
	</p>
</form>

When you have a form where you need to upload a file you must add enctype=”multipart/form-data” in the form open tag.

if (isset($_POST['submit']))
{
	//form submitted, process data
        print_r($_POST);
}

we check if the form was submitted and we use print_r() to print the values of the form to the browser, just to check if everything works.

Try catch

Now before we start getting the values we are going to implement a very easy to use error checker named trycatch

$feedback = '';
try
{
	$title = addslashes($_POST['title']);
	$title = addslashes($_POST['content']);
}
catch (Exception $e)
{
	$feedback = '<div class="error">' . $e->getMessage() . '</div>';
}

this is very easy, all your code that needs to be executed must go between the curly braces of the try. As soon as an error is thrown the catch will catch (obviously) the thrown error and store it in a variable which you can then print out on the screen to notify the person, who is filling in the form, that he made a mistake.

we also wrap the error message between a div tag with a class error so we can style it and make it a bit more vissible to the user (red background for an error, and green background for success message). Here are some basic styles you can add to your stylesheet.

/*ERROR MESSAGE*/
.error
{
padding: 8px 0px 8px 40px;
margin:5px 0px;
-moz-border-radius:4px;
border:1px solid #BF0008;
background:#FFDFDE url("../images/delete.png") no-repeat;
background-position:10px 10px;
color: #BF0008;
}

.error span
{
	font-weight:bold;
}

.error a:link, .error a:visited
{
color:#BF0008;
font-weight:bold;
text-decoration:underline;
}

.error a:hover, .error a:active
{
color:#FFF;
background:#BF0008;
font-weight:bold;
text-decoration:underline;
}

/*SUCCES MESSAGE*/
.succes
{
padding: 8px 0px 8px 40px;
margin:5px 0px;
-moz-border-radius:4px;
border:1px solid #057100;
background:#DFFFDE url("../images/check.png") no-repeat;
background-position:10px 10px;
color: #057100;
}

.success span
{
	font-weight:bold;
}

.success a:link, .success a:visited
{
color:#057100;
font-weight:bold;
text-decoration:underline;
}

.success a:hover, .success a:active
{
color:#FFF;
background:#057100;
font-weight:bold;
text-decoration:underline;
}

/*INFORMATION MESSAGE*/
.info
{
position:relative;
padding: 8px 0px 8px 40px;
margin:5px 0px;
-moz-border-radius:4px;
border:1px solid #003f73;
background:#DEF0FF url("../images/info.png") no-repeat;
background-position:10px 10px;
color: #003f73;
}

.info span
{
	font-weight:bold;
}

.info span.close_update
{
	position:absolute;
	top:2px;
	right:5px;
}

.info span.close_update a
{
	text-decoration:none !important;
}

.info a:link, .info a:visited
{
color:#003f73;
font-weight:bold;
text-decoration:underline;
}

.info a:hover, .info a:active
{
color:#FFF;
background:#003f73;
font-weight:bold;
text-decoration:underline;
}

/*WARNING MESSAGE*/
.warning
{
padding: 8px 0px 8px 40px;
margin:5px 0px;
-moz-border-radius:4px;
border:1px solid #6E7300;
background:#FEFFDE url("../images/warning.png") no-repeat;
background-position:10px 10px;
color: #6E7300;
}

.warning span
{
	font-weight:bold;
}

.warning a:link, .warning a:visited
{
color:#6E7300;
font-weight:bold;
text-decoration:underline;
}

.warning a:hover, .warning a:active
{
color:#FFF;
background:#6E7300;
font-weight:bold;
text-decoration:underline;
}

Get the submitted values

Now we can start getting te values from the form, we do this using the POST method.

$title = addslashes($_POST['title']);
$title = addslashes($_POST['content']);

It is extremely important to validate what was inputed in the form fields before sending it to the database. When you create forms like registration pages or other forms that require user input, always validate! Never trust a user!

Here we are using addslashes() which should do the job just fine. ( but don’t rely on it completely ) but if you want to validate for specific input (eg: e-mail, url, usernames with no special chars) i recommend you to use a validation class, i won’t go into details as this is beyond the scope of this tutorial.

The thumbnail

Now we need to get the thumbnail and upload it in our images folder and store the path to that image in a variable which will send to the database later on. Unlike text input we use the $_FILES global variable to get the image.

if (!empty($_FILES['thumbnail']['tmp_name']))
{
	$path = 'images/'.$_FILES['thumbnail']['tmp_name'];
	//check if uploading of the image returns any error, then throw an error. If not then do nothing
	if (!move_uploaded_file($_FILES['thumbnail']['tmp_name'], $path))
	{
		throw new exception('Could not upload the image!');
	}
}
else
{
	throw new exception('no image uploaded!');
}

We first check if there is an image and then we upload it and see if an error is returned. (tmp_name is the path where the file is temporarly uploaded before moving it to the images map). We set the path to images/filename, if you don’t specify a filename the upload will fail.

throw new exception() is how we throw our error. Once an error is thrown it will stop on that line and anything below that won’t be executed (but only what’s between the curly braces of the try, it will still display anything below the trycatch). A parameter can be given which is the text that should be displayed to the user.

This is the basic code for uploading a file, it’s extremely important that you validate the uploaded image before storing it on your server. I kept it short because I’ve already written a tutorial on how to check for specific files like images http://blog.cmstutorials.org/tutorials/php-upload-script

Send it to the database

Before we send our data in the database we must add a new column for the thumbnail, in your phpmyadmin go to your database and run the following query:

ALTER TABLE `article` ADD `thumbnail` VARCHAR( 300 ) NOT NULL AFTER `body` 

let’s build our query now.

//if the image was uploaded send everything to the database
$sql = "INSERT INTO article (title, body, thumbnail, date) VALUES ('".$title."', '".$content."', '".$path."', '".time()."')";

Now we’ll execute our query and check if it was not successfull. If it wasn’t successfull we will throw an error which will be catched and displayed to the user.

if(!mysqli_query($link, $sql))
{
	throw new exception('could not run query');
}

By default an if-statement is looking for true, so if the query was excecuted successfully, but in our case we only want to do something when there was an error. Therefor we place a ! (also called a negation) in the if statement, it will check for a false instead of true.

Finally if everything succeeded let’s show a success message

$feedback = '<div class="success">Article successfully submitted!</div>';

You can now print the success or error message anywhere on your page with the following code:

<?php echo $feedback; ?>

Text editor

If you wish to write articles a text editor to speed up the writing and styling of your text is a must. There are a lot of text editors out there, I will use the fckeditor but you might also want to have a look at Tiny MCE or markitup (this last one gives you more controll but is a bit more technical).

Download the zip file and extract it. You should have a ckeditor folder, place that folder in the root of your project (next to addarticle.php and other files and folders). (last version of the editor when this tutorial was written: CKEditor 3.5.2, released on 16 February 2011)

First we must include the ckeditor.js and other js and css files, add the following code in your header.php:

<script type="text/javascript" src="ckeditor/ckeditor.js"></script>
<script src="ckeditor/_samples/sample.js" type="text/javascript"></script>
<link href="ckeditor/_samples/sample.css" rel="stylesheet" type="text/css" />

Replace the open textarea tag with the following:

<textarea cols="80" rows="12" name="content" class="ckeditor">

Of course this is just a sample and if you wish to extend the potential you can always have a look at the documentation of the editor or have a look in the samples folder (inside the ckeditor folder)

Series Navigation

<< Dynamic website part 2

Written by krike

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam sit amet nisl nisl. Ut interdum libero vitae quam ultricies et lacinia elit aliquet. Praesent tincidunt, sem tempus feugiat feugiat, turpis tellus scelerisque erat, sit amet feugiat neque arcu ac lectus. Sed at mi et elit interdum scelerisque vitae eu felis.

krike has written 77 posts.

  • php beginner

    Followed tut part 1 and 2 ! great stuff ! But what the heck happened to part 3 ? its as if you lost intrest in doing this tutorial ….

    • @php beginner: I haven’t lost my intrest at all, I did have a lot of work and because a few people requested a part 3 on how to insert data into a database I then quickly wrote it. Maybe I wrote it a bit to quick. However this does not mean I would never have update the tutorial. Can you specify which parts of the tutorial aren’t clear or what you think could be done better?

      • yusuf

        hy man where i have to put this syntax ???

        if (isset($_POST[‘submit’]))
        {
        //form submitted, process data
        print_r($_POST);
        }

        • krike06

          somewhere at the top of your page between php tags

          • yusuf

            oke kirk thanks, but i have another problem i stuck here i confuse with structure of code in this part sorry man i am verry2 new in program in this part the explanation is to short , can u help me to write your code in this part so that iknow the position from each code, sorry bro..! itry to learn programming with coding, sorry my english bad:)

  • php beginner

    lol perhaps I spoke to soon ! I am greatfull for the stuff you put up here , it has helped me a lot ! I just thought this part seemed rushed. I changed the method slighty as I dont want to upload an image or even articles I was trying to use this method to create a text field on a home page that an end user can change themselfs through a form in the backend. I created a table called main_text and then two columns ,title and body. everything is working and the title and body text are being printed on screen from the database but I cant get the form to send the data to my table. I tryed using the code you supplied and created a thumbnail column to but that didnt work either. any advice ?

  • php beginner

    update: I figured it out ! thanks.

    • @php beginner: glad you worked it out, what was the problem?

  • php beginner

    I wasnt using the correct Syntax to update my existing data (complete noob lol) after some research I found the correct syntax on the MYSQL Mannual. After that I just needed to remove the code related to the image upload and it all seems to be working well 🙂 if I wanted to update images in a jquery slider would the proccess be similar to this ?

  • Muqeet

    Hi Krike…

    I am a new web developer. How i can make dynamic website with an administration panel also. Like in E-commerce website we have a admin section through which we can change pictures text etc…

    Waiting your reply.

    Kindest Regards,
    Muqeet

    • @Muqeet: we’ll..,

      first you would have to create a membership system that will allow you register & login
      also create user group system (admin, moderator, members,…)
      Once you have that you can create a new folder named admin where you add your admin pages
      you also create a header.php & footer.php for your admin panel and in there you check if you have admin priviliges

      I know it’s a bit short but explaining how to create an admin panel in a comment isn’t really the easiest thing to do.

  • I have gone through all of your post on Dynamic Website part 1, 2 and 3. This is really wonderfully written covering almost many important aspects and hence are so helpful for newbies
    Please let us know how set up an Admin section for a website, so that client can update photos, feedback or guestbook entries at their own, with ease.
    Thanks

    • @Samar: Thank you for your comment. Another person requested a similar tutorial and therefore I will cover how to create a membership system in part 4 (and maybe part 5) of this tutorial serie.

  • Bou

    How can you get the last posted article to show first? If you now post a new article it show on the last page.

  • Bou

    nvm i found out already 🙂
    Thanks for you awesome tutorials btw!! They’ve been a great help! Can’t wait for part 4 and 5!

    • @Bou: glad you found it 🙂 I’ll still answer your question for other people who wish to know how to do this as well.
      You can achieve this very easily by adding ORDER BY date DESC to your mysql query

  • John

    When will part 4 be out?

    • @John: I cannot give you a specific date. Maybe end of this or next week

  • fred

    hi,

    i have a problem with the thumbnails. When i use this code:
    thumbnail; ?>
    It only shows the path to the image that i wanted to display. So I tried fitting the tag in. Which resulted in the following:

    <?php echo '’; ?>

    This shows a box with a question mark inside, which implies that the image couldn’t be found? What to do?

    • @fred: the code you pasted looks a bit messed up, best way is to create a new snippet at and link to that snippet instead of copy pasting code in the comments.

  • John

    Hi krike,
    No problem, I have a problem though, my thumbnails arent showing but they are being uploaded into the Database because I can see them in there. So thats not the problem. I noticed that in the article.php there isnt any code echoing the thumbnails? Perhaps theres a line like that missing?

    Also when I use the texteditor(addarticle.php) you supplied it uploads whatever text i put in correctly and it shows on the article.php page but when i insert an image lets say half way through a paragraph of text it also doesnt show up. Im using the default image button thats in the text editor where you link a url.

    Its just the images are the only problem im having. Besides that its perfect! Thank you so much!

    • @john: yes it could be I forgot to add it in the previous tutorial or I decided to add it in this tutorial but forgot to update the previous one. I will correct this issue asap. I did not test uploading images, maybe there is a setting like a link to the folder where the images are being uploaded that is in correct. I will check that asap.

  • fred

    Ok so I have a field called ‘thumbnail’ in the table ‘article’. The part of storing the image path into the database is working. Taking it out of the database seems to work aswell. Only I can’t get it to display the image. Here’s the code I’m using for it.

    Which results in the blue box with a questionmark

    • @fred: just echo it out, echo $myvar['thumbnail']; and see what path it prints out. The image path must be correct otherwise he won’t find the image. you can also use the $siteurl variable like so echo $siteurl . $myvar['thumbnail'];. It’s an example, not sure how your images map structure looks like but if you followed everything it should be something like

  • pj

    HI Man, thanks a lot for the tutorial.

  • gre

    hey im stuck here
    my form is display with errors but once i push submit btn it isnt inserted into the database
    plz can u provide me link to your complete project file of this series
    thanks i need it plz

    • krike06

      What kind of errors do you have? Post the errors