Saving CKEditor data to MySQL Database

October 28th, 2011

Yesterday, I needed to give a client a What-You-See-Is-What-You-Get (WYSIWYG) editor for a text-area.  So, I’m thinking, “ahhh, no problem, should take about 30 minutes…”  I figured I could just whip up some jquery that would call a PHP page to submit the CKEditor information to the database.

While that may have been possible, I decided to look into the CKEditor API documentation and found that there is an easier way.  You will also need the jquery.form plugin, which can be downloaded here. Let’s look at the code for the index.php file (I always use the PHP file type instead of htm* because I may need to insert some php code sometime… only for testing pages, though, not production):

<!DOCTYPE html>
<html>
    <head>
        <title>Writer</title>
        <meta content="text/html; charset=utf-8" http-equiv="content-type" />
        <script type="text/javascript" src="ckeditor/ckeditor.js"></script>
        <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
        <script type="text/javascript" src="jquery.form.js"></script>
        <style>
            .cke_contents {
                height: 400px !important;
            }
        </style>
    </head>
    <body>
        <form action="result.php" method="post">
            <textarea class="editor" id="editor" ></textarea>
            <script type="text/javascript">
                //<![CDATA[
                CKEDITOR.replace( 'editor',
                {
                    fullPage : true,
                    uiColor : '#9AB8F3',
                    toolbar : 'MyToolbar'
                });
                //]]>
            </script>
        </form>
    </body>
</html>

Note that the only purpose for having the form element is to enable the save button, we will be saving this with jQuery, so there will not be an actual form submission.

In the javascript here, we are using the .replace() function from the API to replace the control whose ID is ‘editor’, then setting the editor to be the fullPage width, setting the color for the interface, and telling it to use a custom toolbar named ‘MyToolbar’.

If you haven’t already downloaded the ckeditor, you can get the latest here.  Extract the zipped (or tar-gzipped) file into the root of your site directory.

Now for the ckeditor plugin, open to the directory ‘ckeditor/plugins’ and create a new directory called ‘ajaxsave’ and, in that directory, create a new file called ‘plugin.js’.  Now let’s put the following code in that file:

CKEDITOR.plugins.add('ajaxsave',
    {
        init: function(editor)
        {
            var pluginName = 'ajaxsave';
            editor.addCommand( pluginName,
            {
                exec : function( editor )
                {
                    $.post("result.php", {
                        data : editor.getSnapshot()
                    } );
                },
                canUndo : true
            });
            editor.ui.addButton('Ajaxsave',
            {
                label: 'Save Ajax',
                command: pluginName,
                className : 'cke_button_save'
            });
        }
    });

Basically, what is happening is we are adding a command to a button known as ‘ajaxsave’ in the toolbar and telling it to post to the file “result.php” the data contained in the editor using the getSnapshot() function from the API.

Now I chose to only give a subset of commands available along with my newly created and defined “Ajax Save” button by modifying the “config.js” file for the CKEditor (found in /ckeditor/):

/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/

CKEDITOR.editorConfig = function( config )
{
    // Define changes to default configuration here. For example:
    // config.language = 'fr';
    // config.uiColor = '#AADC6E';

    config.uiColor = '#AADC6E';
    config.resize_enabled = false;

    config.toolbar = 'MyToolbar';

    config.toolbar_MyToolbar = [
        ['NewPage','Preview','Ajaxsave'],
        ['Cut','Copy','Paste','PasteText','PasteFromWord','-','Scayt'],
        ['Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'],
        ['Table','HorizontalRule','Smiley','SpecialChar'],
        '/',
        ['Styles','Format'],
        ['Bold','Italic','Strike'],
        ['NumberedList','BulletedList','-','Outdent','Indent','Blockquote'],
        ['Link','Unlink','Anchor'],
        ['Maximize','-','About']
    ];

    config.extraPlugins = 'ajaxsave';

};

For a complete list of all non-custom buttons, see the documentation at the bottom of this page for them.

Now to actually save it to the database.  Create a new PHP file, result.php, in the same directory as your index.php file and use the following code as a sample to insert the data into the database…

<?php
  $host   = 'localhost'; // alternatively, you can put '127.0.0.1' here
  $dbUser = 'root'; // I would never use root for a production
                    // user, but for a local installation, it is ok...
  $dbPass = '1234'; // or whatever it is set to be...

  $dbName = 'test'; // use your database name here
  $dbConn = mysql_connect($host, $dbUser, $dbPass)
                  or trigger_error(mysql_error(), E_USER_ERROR);
  mysql_select_db($dbName, $dbConn);

  /* Table:  messages
   * Fields: id      (INT, primary key, auto-increment)
   *         message (TEXT)
   */
  $sql = "INSERT INTO messages VALUES(NULL, '" . mysql_real_escape_string($_POST['data']) . "';";
  $queryResource = mysql_query($sql, $dbConn) or die(mysql_error());
?>

I hope this helps, please comment below!

Bud Manz
Owner – Manz Web Designs, LLC

http://www.manzwebdesigns.com/