Integrating FCKeditor With Your MySQL Database
Written By Michael on May.24.2007
This article is intended to address the lack of documentation in integrating the FCKeditor with your MySQL database. Their tutorials show how to configure and use the editor, but how to get it to save to your database isn't addressed at all. While this article will utilize the MySQL DBMS, the concepts are the same for any DBMS. On the same token, all my examples will assume your webserver is running a flavor of Linux and PHP 4.3.0 or higher, but the concepts will be the same on any webserver.
Step 1 - Install FCKeditor
We'll start off with a brief tutorial to get FCKeditor up and running on your website. First, download FCKeditor. After it finishes downloading, the quickest way to install it is to upload the .tar.gz file to your webserver and then unpack it there rather than upacking it on your computer and uploading the entire folder to your server which is several times larger and consists of hundreds of files. Once you upload the file, run the following commands:
cd /path/to/file
tar -xvzf FCKeditor_2.4.2.tar.gz
Next, move the folder to where you want all the files to be located. I always put them in my includes directory.
mv FCKeditor_2.4.2 /path/to/www/includes/FCKeditor
Step 2 - Put FCKeditor On A Webpage
Create the following skeleton webpage in your webroot directory (/path/to/www from the examples above):
File: index.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Test FCKeditor</title>
</head>
<body>
<h1>Test FCKeditor</h1>
</body>
</html>
Now that we have our basic webpage up and running, we need to add the editor to it. First, we have to include the class file for the editor. Place this code at the very beginning of index.php:
<?php
include_once "includes/FCKeditor/fckeditor.php";
?>
Then, below the <h1> tag, insert the following code:
<?php
$oFCKeditor = new FCKeditor('fcktext');
$oFCKeditor->BasePath = "/includes/FCKeditor/";
$oFCKeditor->Value = "";
$oFCKeditor->Width = 540;
$oFCKeditor->Height = 400;
echo $oFCKeditor->CreateHtml();
?>
Now refresh index.php in your web browser and you should have something that looks like this:

Voila, you've successfully installed and setup your very own WYSIWYG editor. Feel free to play around with it and test out the various options. The image browser won't work because we haven't set that up. For more information on how to configure it, see FCKeditor's website.
Step 3 - Saving To A Database
I'm sure you've noticed the save icon ( ) in the editor. Sure would be nice if it actually did something like save the text you've typed in the editor, huh? Well that's actually really easy to do. First, we need a database. For this example, we'll use a very simple table. I'm going to assume you are able to create a MySQL database and that your PHP installation has the proper libraries installed to connect to it. If not, see MySQL's website for more information on that. To create the table, simply run the following query against your database:
CREATE TABLE `fck_data` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`data` TEXT NOT NULL
) ENGINE = MYISAM ;
That query will create a table called fck_data with 2 fields:
| Field Name |
Type |
Description |
| id |
integer |
primary key |
| data |
text |
data from fckeditor |
Next, we need to enclose the editor in a basic form so the data we enter can be submitted to the server:
<form action="index.php" method="post">
<?php
$oFCKeditor = new FCKeditor('fcktext');
$oFCKeditor->BasePath = "/includes/FCKeditor/";
$oFCKeditor->Value = "";
$oFCKeditor->Width = 540;
$oFCKeditor->Height = 400;
echo $oFCKeditor->CreateHtml();
?>
<br />
<input type="hidden" name="submit_form" value="1" />
<input type="submit" value="Save Form" />
</form>
Now we need to handle the POST the form will make to the server. Since the action of our form is the same page that the form is on, we can just insert the following at the top of index.php:
<?php
if ($_POST['submit_form'] == 1) {
// Save to the database
// Redirect to self to get rid of the POST
header("Location: index.php");
}
?>
This if statement will be executed each time the form is submitted. The hidden attribute called submit_form in the form gets the value of 1 each time the user submits the form. The if statement looks for it in the $_POST array and if it's there, then we know the user submitted the form and we need to do something. At the end of the if statement, we use a call to the php function header() to redirect the page to get rid of the POST. What this accomplishes is that if the user refreshes the page after clicking submit, they are not prompted that the page has expired and they need to resubmit the form. The page will simply refresh as expected.
As for the actual saving to the database, it isn't quite this simple. There are a couple of other things I need to mention. First, when saving the data to the database, there are two possible actions: either we're inserting a new record or we're updating an existing one. Each of these has its own unique SQL query. Moreover, the first time we use this form and click save, we will need to insert the record and then every time after that we will need to fetch the record's contents, display them in the editor, update the record in the database if the user clicks submit, and then repeat.
So how do we accomplish this? Well there's actually numerous ways. For the sake of simplicity and to keep this article on course, I'm going to just manually create the record and then we only have to worry about updating the record. To create the first record, run this query on your database:
INSERT INTO fck_data SET id = 1, data = "";
Now that the database and table are setup, let's make a connection to it in our file. Place this code at the beginning of the file before the if statement:
<?php
$cnx = mysql_connect("localhost", "username", "password")
OR die("Unable to connect to database!");
mysql_select_db("database_name", $cnx);
?>
And then at the end of the file, add this code:
<?php
mysql_close($cnx);
?>
Now we've got our script connected to the database and ready to start doing some updating. Before that, though, let's make sure our editor is automatically populated with data from the database. Modify the code that displays the editor to the following:
<?php
$query = mysql_query("SELECT data FROM fck_data WHERE id = 1");
$data = mysql_fetch_array($query);
$oFCKeditor = new FCKeditor('fcktext');
$oFCKeditor->BasePath = "/includes/FCKeditor/";
$oFCKeditor->Value = $data["data"];
$oFCKeditor->Width = 540;
$oFCKeditor->Height = 400;
echo $oFCKeditor->CreateHtml();
?>
Two changes have been made. The first was the addition of the functions mysql_query and mysql_fetch_array. The first executes a query and returns a resource ID for the result set. The second fetches the first row from the result set and returns it as an array. This array is stored in the $data variable. The other change is to the line $oFCKeditor->Value = $data["data"];. That is where we populate the editor with the value from the database. The key "data" in the array is the field name from the table that stores the data from the editor.
Finally, we need a way to update the database with any modifications we make to the text in the editor. Since we already have our if statement ready to capture the POST data from the form, we just need to insert the following code into that if statement:
<?php
$data = mysql_real_escape_string(trim($_POST['fcktext']));
$res = mysql_query("UPDATE fck_data SET data = '".$data."' WHERE id = 1");
if (!$res)
die("Error saving the record! Mysql said: ".mysql_error());
?>
The first line takes the text typed in the editor, trims it (which means it removes all leading and trailing white spaces), then adds any necessary escape characters so it can be safely inserted into the database without fear of sql injection. Now, assuming you've done everything right, you should have a working FCKeditor that saves your text to the database. To test it, type something into the editor and click save. Then close the browser and reopen it and your text should still be there.
Remember the save icon ( ) from earlier? Clicking that icon generates a form submit, so you can also click that icon instead of clicking the save button below the editor. I know we've done a lot of work to the file, so below I have the full index.php file with all the updated code:
File: index.php
<?php
// Connect to the database
$cnx = mysql_connect("localhost", "username", "password")
OR die("Unable to connect to database!");
mysql_select_db("database_name", $cnx);
if ($_POST['submit_form'] == 1) {
// Save to the database
$data = mysql_real_escape_string(trim($_POST['fcktext']));
$res = mysql_query("UPDATE fck_data SET data = '".$data."' WHERE id = 1");
if (!$res)
die("Error saving the record! Mysql said: ".mysql_error());
// Redirect to self to get rid of the POST
header("Location: index.php");
}
include_once "includes/FCKeditor/fckeditor.php";
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Test FCKeditor</title>
</head>
<body>
<h1>Test FCKeditor</h1>
<form action="index.php" method="post">
<?php
// Get data from the database
$query = mysql_query("SELECT data FROM fck_data WHERE id = 1");
$data = mysql_fetch_array($query);
// Configure and output editor
$oFCKeditor = new FCKeditor('fcktext');
$oFCKeditor->BasePath = "/includes/FCKeditor/";
$oFCKeditor->Value = $data["data"];
$oFCKeditor->Width = 540;
$oFCKeditor->Height = 400;
echo $oFCKeditor->CreateHtml();
?>
<br />
<input type="hidden" name="submit_form" value="1" />
<input type="submit" value="Save Form" />
</form>
</body>
</html>
<?php
// Close the database connection
mysql_close($cnx);
?>
Conclusion
This article was a very basic overview of how to save your text in the FCKeditor to your database. We assumed you would only be working with one record in the database the entire time, but that isn't very practical. With some additional coding, you could have a page that listed all the records in that table, and allowed the user to select one to modify or just add a whole new one. The possibilities are endless, but hopefully this article has given you the necessary foundation to expand these concepts into more complicated applications.
Comments
Brandon Roloff said on May.24.2007 12:46 PM...
Thanks alot for this article. I played around with fckeditor for days and researched their wiki site and their message forums and I was unable to find a decent explanation of how this works and how to integrate this into mysql.
desbest tynamite said on May.29.2007 9:43 AM...
This is so helpful to any person making a script. Thanks alot, you're helping alot of ppl.
Raymond E. Korns said on Jun.10.2007 11:14 PM...
Great! Really appreciated your taking the time to create this page. So many excellent tools are documented only as standalone demo's with no explanations on how to connect them to do anything useful. This little tutorial saved me hours of work.
Redostrike said on Jun.19.2007 9:39 AM...
Thanks for this. I had no clue in how to add the fckeditor text into a database. I love your tutorial. I used Dreamweaver (i always use dreamweaver) and i used a bit of the suggestions you posted.
Thanks for this.
Deepak Saxena said on Jun.27.2007 2:53 PM...
Thanks very much for this article. This is very easy to understand and I didn't face any problem. I have one question that when I am trying to save the data it takes me on the same page by saying page can not be displayed but the data is getting saved to the database.
One more problem is the formatting is getting lost when I am saving the data.
Please suggest me what should I do if I want to retain the formatting as I did in the editor.
Thanks
Deepak
msbware said on Jul.03.2007 2:37 PM...
Deepak -
It should retain the formatting right out of the box. If it's not, double check how you're saving the data into the database and how you're calling it out of it before sending it to FCKeditor. You're probably doing something that is stripping the html entities.
As far as your "page cannot be displayed" error, my guess would be you named the file something other than index.php. In that case you would need to change the following line of code:
header("Location: index.php");
to
header("Location: {your filename}");
Where {your filename} is whatever name you chose for your file. Hope that helps.
Wayox said on Jul.09.2007 11:55 PM...
Hi, great tutorial.
But i have this problem...
When I hit the edit buttom i created to call back from my MySQL DB it only appears the first letter...
What could that be??
Thanx
govokinolij said on Jul.10.2007 7:15 AM...
Hi all!
Looks good! Very useful, good stuff. Good resources here. Thanks much!
G'night
James Schmittler said on Jul.13.2007 1:38 PM...
I'm getting extra \'s in my code. For example when i want to add a link its adding \"google.com\" for example which in turn doesn't work in the browser. Any suggestions?
msbware said on Jul.16.2007 9:11 AM...
Wayox > I'd have to see your code in order to see what's going on.
James > try using the stripslashes() function. eg:
<?php
$oFCKeditor->Value = stripslashes($data["data"]);
?>
James said on Jul.18.2007 3:31 PM...
I got it to work. There was a conflict with magic quotes. Now I'm on to getting the image uploader to work. It says the image successfully saved to the database but the image doesnt actually save it anywhere and i can't see it. any help?
msbware said on Jul.23.2007 9:01 AM...
James > You'll have to configure the upload directory (which defaults to /UserFiles) and then change the permissions to make sure it's writeable by the web server. If you're running linux, the command would be:
chmod 777 /path/to/UserFiles
Nicole said on Aug.19.2007 9:22 PM...
$query = mysql_query("SELECT data FROM fck_data WHERE id = 1");
How would you change the Where clause to filter by a post instead of the entered value?
msbware said on Aug.22.2007 9:21 PM...
The simplest way is like this. It works, but it can lead to some possible sql injections.
$query = mysql_query("SELECT data FROM fck_data WHERE id = '".$_POST['id']."' ");
One way to prevent any malicious data being entered, do this if you have php 4.3 or newer:
$query = mysql_query("SELECT data FROM fck_data WHERE id = '".mysql_real_escape_string($_POST['id'])."' ");
Sendhil Mani R said on Aug.30.2007 1:46 AM...
Hi All,
This page has been very useful. I want to know whether is there a way to connect to MySQL database through JSP from FCK editor. If this is possible please do send me some leads as of how to do it. I need to connect to MySQL database through JSP from FCKeditor.
Regards,
Sendhil
Vgparis said on Aug.31.2007 4:59 AM...
excellent thanks a lot!!
i tried to use FCK to manage differents webpages but i don't know how to change the php code :/
Tossican said on Sep.15.2007 1:58 PM...
Fantastic article/tutorial. Thanks for putting the help out there!
I have been searching for a solution to an odd problem I am having, and about to pull my hair out, perhaps someone here can help?
My form works awesome, data is saved, data is retrieved and pulled back into the editor. No problem here.
The problem is displaying the data on another page. I seem to be getting loads of " " codes added into the data. and it's totally throwing off the formatting when displayed outside of the editor. It especially messes up tables, as it results in something like:
<table> <tr> <td> Stuff
</td> </tr> </table>
I suppose I could do a string replace to remove them. But if it's caused by an improper setting somewhere, I would rather fix it, then work-around it.
Thanks for any help possible!
-- Tossi
msbware said on Sep.18.2007 9:41 PM...
Tossi >
Are you typing the HTML code directly into the WYSIWYG editor? If so, then it will put those tags in there for each space. If you want to edit the HTML code itself, click on the "Source" icon in the editor and do it that. If that's not the case, then I can't think of anything off hand. There's no reason it should put those characters in the table code like that. I'd have to see your code to know for sure in that instance.
Hope that helps
Hans said on Sep.19.2007 10:11 PM...
I tried that on my LAMP system and 'seems' to work. The problem is, if I change the color of the text, let's say to red or yellow or blue, and I save it, suddenly the color turns to green, always green! Any idea why?
The weird thing also happens to background color of text. Never works although it looks OK on editing mode, but just gone when I save it.
Tossican said on Oct.03.2007 7:34 PM...
msbware >
I have the 'source' button turned off in FCK as this will be a psudo 'public use' editor and I don't want people getting any sort of crazy ideas. If there isn't a button turned on for them to do 'special things', I don't want them even trying.
I would be happy to share the code with you, but I'd rather not weigh this page down with a bunch of stuff of no use to anyone else. So, if you could please email me tossican at gmail, I would be happy to forward the appropriate bits on to you, and a link to the resulting page.
Thanks for your help :)
peter said on Oct.03.2007 11:10 PM...
I am trying to make it possible to select which id to work on:
$query = mysql_query("SELECT data FROM fck_data WHERE id = '".$_GET['id']."' ");
this works with the url:
index.php?id=2
It loads fine from SQL, but I cannot get it to write back to the database.
How do I write this line to send the same id?
$res = mysql_query("SELECT data FROM fck_data WHERE id = '".$_GET['id']."' ");
Emanual said on Oct.13.2007 2:49 AM...
This is perfect...Made life soooo easy for the first step.
I'm having the same problem as peter. I can get content from the database based off of the id in the url but can't seem to post back.
If anyone has sorted this out a quick post would really rock...
Thanks
emanual said on Oct.13.2007 2:09 PM...
Test submitting code...
(<? $res = mysql_query("SELECT data FROM fck_data WHERE id = '".$_GET['id']."' "); ?>)
emanual said on Oct.13.2007 2:15 PM...
This has been a very very very useful post. Can we push it a bit farther now.
Everything is working,
Now it would be great to be able to post to whatever id you want by grabbing the id from the address bar. If any of you have figured this out please let us know.
I'll keep working on it and will post for sure if I get it working. I'm a newbie so might take a while.
Thanks in advance if somebody posts before I find the solution
gowest said on Dec.05.2007 4:48 AM...
We found problems in the colors with the function "mysql_real_escape_string"
Gowest said on Dec.05.2007 4:50 AM...
We found problems in the colors with the function mysql_real_escape_string
QuantumPHP said on Dec.20.2007 12:13 PM...
There is a Video tutorial on integrating FCKeditor in MYSQL it's at
http://www.easykiss123.com/?p=24
It's very similar to this article with a few modifications.
Enjoy
Robert Dingwall said on Jan.01.2008 1:45 AM...
Excellent stuff, has helped me endlessly.
Many thanks.
mancoeg said on Feb.04.2008 6:19 AM...
great tutorial
after i upload a photo to the server it appears like an icon on the page
should not it appears like a thumbnail
thanks
mancoeg said on Feb.04.2008 8:04 AM...
also i wrote contact us and i linked it and as you see below
http://localhost/fckeditor/\"/contact.php\"
and this error message appears
Not Found
The requested URL /fckeditor/\"contact.php\" was not found on this server.
msbware said on Feb.10.2008 11:35 PM...
mancoeg > Try removing the quotes from the URL
DamionKutaeff said on Mar.22.2008 2:34 PM...
Hello everybody, my name is Damion, and I'm glad to join your conmunity,
and wish to assit as far as possible.
Riri said on Apr.03.2008 8:08 AM...
Hello all, I've spent days to understand 'bout FCKEDItor...
this article helps me alot...
I tried everything in this article, when it comes to images, this script isn't working.
I've checked @mysql, and the data exist ...
but when i called the data using fck editor, there's nothing in it,
Please Help :)
Thanx
Levi said on Apr.09.2008 11:29 AM...
[code]Is there a way to use css with this?[code]
thanks,
Levi
Anil said on Apr.25.2008 3:52 AM...
I am using this code for create editor in my php pages, everything is write but text color, image is not working so plz help me.
wbondarmunw said on Apr.29.2008 9:42 PM...
Hello!
I yearning that chose the decent segment of it for asking your inconceivable, if not, sorry.
I do not uncertainlyably continually go to the forums. And my, my assuredly is what is:
How do you deliberate on how sincere the conundrum of charge increases, and whether it is plausible far-reaching shock,
the actuality that already event, namely: Rising stuffs tolls has transformed stuffs into an global partisan issue.
Riots prepare erupted in Egypt, Haiti and Bangladesh in excess of soaring stuffs charges.
People fought one another closed bags of rice in West Africa.
The causes and the solutions to the stuffs calamity are complex.
Iif not tough and you pull someone's leg your notion on this, suit response, I am unundoubtedlyably interested to pick up your theory.
Tthank you
P.S. Sorry for my english.
patrik said on May.22.2008 9:34 PM...
h1IHTK jr39ug7djalfgpitg94gbvm
Claudio said on Jun.11.2008 2:56 PM...
Hello everyone, my problem is that i need to be able to post to whatever id you want by grabbing the id from the address bar.
I alredy have 6 days working on it and nothing
If you guys can help me!! please!!
Constructive Visual said on Jun.13.2008 10:43 AM...
Is there any way of having multiple fckeditor's on the one page editing data out of mysql database?
I have tried many things without any success.
Ben said on Jun.15.2008 4:30 PM...
This is brilliant, I used the video tutorial from easykiss123, it helped. One questions, now I want to progress and have different fields from the same database to edit different sections/pages - I thought I would know how to do it, but as my MySql knowledge is poor and I'm a little shady about creating a fesh table in myphpadmin and then knitting into the code we already have - any help would be lovely!
Alidad Modjtabai said on Jun.28.2008 6:41 PM...
this is great, is what i'm looking for. thanks so much.
another things is that do you have any sample how to setup path for image or upload image or insert images into fckeditor!
AM
|