Posting MySQL data back to the CKEditor instance

NOTICE: UPDATED TUTORIAL USING PDO INSTEAD OF THE DEPRECATED MYSQL_ METHOD CAN NOW BE FOUND AT https://manzwebdesigns.com/2013/07/17/save-retrieve-ckeditor-data-pdo-mysql/!

Hello,

This a follow-up to the post,  Saving CKEditor data to MySQL Database, that shows how to bring the data back from the MySQL database into the CKEditor instance.  This is fairly simple to accomplish, so I will post the code for the updated page and then go through the new code step by step and explain what is happening!

<?php
  // include the database configuration file
  include 'includes/config.inc.php';
  // make the connection using the credentials from the include file
  $dbConn = mysql_connect($host, $dbUser, $dbPass)
             or trigger_error(mysql_error(), E_USER_ERROR);
  // select the database for use
  mysql_select_db($dbName, $dbConn);
  /* Table: messages
   * Fields: id (INT, primary key, auto-increment)
   * message (TEXT)
   */
  // select the most recent message
  $sql = "SELECT * FROM messages ORDER BY id DESC LIMIT 0,1";
  // query the database, returning a resource containing the data
  $queryResource = mysql_query($sql, $dbConn) or die(mysql_error());
 ?>
<!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="js/jquery.form.js"></script>
    <style>
      .cke_contents {
        height: 400px !important;
      }
    </style>
    <script type="text/javascript">
      $(document).ready(function() {
        CKEDITOR.replace( 'editor',
          {
           fullPage : true,
           uiColor : '#9AB8F3',
           toolbar : 'MyToolbar'
          });
      });
    </script>
  </head>
  <body>
    <form action="result.php" method="post">
      <?php
        while ($row = mysql_fetch_assoc($queryResource)) {
          $content = $row['message'];
        }
      ?>
      <textarea class="editor" id="editor" name="editor"><?php echo $content; ?></textarea>
      <div id="messages"></div>
    </form>
  </body>
</html>

At the top of the file, you will notice that I created an include file that provides all the database connection information.  By doing this, I have a central location to change my credentials in one place instead of having to search through all my files to find them.  This can be a huge time saver if you are working on a project with many files…

  // include the database configuration file
  include 'includes/config.inc.php';

Then, using the credentials from the config file, I establish a connection to the database…

  // make the connection using the credentials from the include file
  $dbConn = mysql_connect($host, $dbUser, $dbPass)
             or trigger_error(mysql_error(), E_USER_ERROR);
  // select the database for use
  mysql_select_db($dbName, $dbConn);

which I then use to query against and retrieve the data we wish to display in our CKEditor…

  // select the most recent message
  $sql = "SELECT * FROM messages ORDER BY id DESC LIMIT 0,1";
  // query the database, returning a resource containing the data
  $queryResource = mysql_query($sql, $dbConn) or die(mysql_error());

Now, we skip down into the <body> section and pull the data back out of the query resource and put it in a variable named $content…

      <?php
        while ($row = mysql_fetch_assoc($queryResource)) {
          $content = $row['message'];
        }
      ?>

Finally, we echo the $content variable out into the textarea and let CKEditor pull it in!

      <textarea id="editor" name="editor"><?php echo $content; ?></textarea>

I hope you enjoy this tutorial and ask you to comment if it isn’t clear to you.

Thanks,
Bud Manz
http://www.manzwebdesigns.net/
Where your web comes to life!

17 thoughts on “Posting MySQL data back to the CKEditor instance”

  1. Landed on this site as it’s the closest I’ve seen that provides tutorial/explanation of using CKEditor with content in a database. A couple of days ago I come across the https://manzwebdesigns.com/2011/10/28/saving-ckeditor-data-mysql-database/ and was happy with making some progress. But what about fetching data data from a database? I landed on this page and got something working along the lines of:-

    require_once(“model/config_msg.php”);

    $source = $_GET[‘cuid’];

    // select the most recent message
    $sql = “SELECT * FROM messages where id=$source”;
    // query the database, returning a resource containing the data
    $queryResource = mysql_query($sql, $dbConn) or die(mysql_error());
    while ($row = mysql_fetch_assoc($queryResource)) {
    $content = $row[‘message’];
    }

    <input type="text" name="cuid" value="”>

    Worked as expected – fetched and displayed the content. But I was stumped on the obvious next step – updating the content in the editor and saving it back to the database. I tried a few things and I couldn’t even get it to write anything back to the database. No updates and not even inserting a new record.

    I then noticed (using Firebug) that even though I modified the content in ckeditor, firebug was still showing the previously fetched content. The bit contained in the was not being updated.

    If I can get past this hurdle then the next one would be how to get the Ajaxsave button to pick up other form elements and $.post these back to the server-side script update my content as well as other fields that may be posted back from the form.

    Any hints?

    1. Hi,

      Sorry about the delay, somehow I missed your post!

      When you update the ckeditor, it does not update the DOM (Document Object Model) until it gets posted. As far as how to get the Ajaxsave button to pick up other form elements, I haven’t tried that, perhaps that would be a good next tutorial?

      Let me know how you make out.

      Thanks,
      Bud

    1. Hi Mitt,

      You should have been able to just update the file index.php from the first tutorial with the additional code. Did you create a config.inc.php file and put the same credentials from results.php in it? Also be sure that the config.inc.php file is in a http root directory for the site named includes.

      HTH,
      Bud

      1. Hi Bud,

        I did that and it’s not working. I think i might have to redo the files from the previous lesson and read closely to the this lesson instructions.

        I mean the only thing I put was add this

        The weather is pretty hot so drank plenty and stay cool! I live in NY it’s really hot yesterday. I will let you know what I did wrong or maybe I am can pinpoint the issue.

        I have question can I get that page without using that ckeditor? My SQL is not good but $get[message] the data from the things I wrote on to the webpage. I just want to see how it works. I don’t know how to explain ‘echo’ the data. This had nothing to do with the lesson but I notice this lesson you add more php and sql got me confuse. Thanks

  2. Hi Bud,

    I’m still having problems. Making the data appear on the CKeditor?
    I’m frustrated now. Is this the issue:

    $dbUser = ‘root’; // I would never use root for a production

    I used my DB name instead of ‘root’

    It work for the first lesson but now I don’t know.

    Any suggestions?

  3. Hi,
    Things are made easier now in CKEditor with contenteditable and CKEDITOR.instances.Text_To_Update.getData
    Works perfectly with my provider, but struggling to make it work on local machine.

  4. Hola e seguido todo el tutorial pero aun no logro agregar el botón estoy ocupando la ultima versión de ckeditor que puedo hacer ayuda porfavor

    Hi I followed everything the tutorial but still can not get to add the button to save the information in the database’m taking the latest version of ckeditor I can do help please

  5. Hi Bud,
    I’ve used you code of saving data of CKeditor to mysql database, it is working properly. But i’m stuck to fetching the deta from mysql database. I used your code but still not working. Can you please help me. I request you to update step by step full explanation of “How to fetch data from mysql and after editing it how to save it back to mysql”.

    Thanks,
    Sajed.

    1. Hi Sajed,

      Thank you for visiting my blog! I am going to recommend that you not use this code because the mysql_ functions are deprecated. I am hoping to redo the tutorials using PDO and adding sanitized inputs using the filter_var functions soon.

      Perhaps you could explain what is happening? Are you getting errors, or is it just not updating the database?

      Thanks,
      Bud

  6. Hi Bud,
    for saving in database is Ok.
    Now i get this code, no database, but i use include:

    //

    But when i save ckeditor add slash ( \) more..more…more

    I get source code

    \"

    and then
    \"\\"

    \"\\"\\\\"\\\\\\\\"

    and it keeps growing every time I submit a form in ckeditor texarea
    can you help me?’
    Best regards
    Adolfo Baldaccini Italy

Leave a Comment

Scroll to Top