Add and Save CKEditor 5 data to MySQL database with PHP

CKEditor 5 is a rich text editor. It has a wide range of features that are meant to make the user’s experience as pleasant as possible.

In this tutorial, I show how you can initialize CKEditor 5 with file upload on the element and save its data to the MySQL database with PHP.

Add and Save CKEditor 5 data to MySQL database with PHP


Contents

  1. Table structure
  2. Database Configuration
  3. Download and Include
  4. HTML & PHP
  5. AJAX – CKEditor file upload
  6. JavaScript
  7. Output
  8. Conclusion

1. Table structure

I am using messages table.

CREATE TABLE `messages` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `subject` varchar(80) NOT NULL,
  `message` TEXT NOT NULL
);

2. Database Configuration

Create a config.php for database configuration.

Completed Code

<?php

$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "tutorial"; /* Database name */

$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
    die("Connection failed: " . mysqli_connect_error());
}

3. Download and Include

  • Download CKEditor 5 library from here or you can use CDN –
<!-- ckeditor5 JS -->
<script src="https://cdn.ckeditor.com/ckeditor5/35.4.0/classic/ckeditor.js"></script>

4. HTML & PHP

HTML

Create a <form method="post" action="" >. In the <form > add a textbox, textarea, and a submit button.


PHP

If <form > is submitted then read the POST values and assign them to the variables. If values are not empty then insert a new record in messages table.

Completed Code

<?php 
include "config.php";

// Insert record
if(isset($_POST['submit'])){

      $subject = $_POST['subject'];
      $message = $_POST['message'];

      if($subject != '' && $message != ''){

            mysqli_query($con, "INSERT INTO messages(subject,message) VALUES('".$subject."','".$message."') ");
            header('location: index.php');
      }
}

?>

<!DOCTYPE html>
<html>
<head>
     <meta charset="utf-8">
     <meta name="viewport" content="width=device-width, initial-scale=1">

     <title>Add and Save CKEditor 5 data to MySQL database with PHP</title>

     <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" >

     <style type="text/css">
     .ck-editor__editable {
           min-height: 250px;
     }
     </style>

</head>
<body>

     <div class="container">
          <div class="row">
               <div class="col-md-8 mt-5" style="margin: 0 auto;">

                    <form method="post" action="">

                         <div class="form-group mb-4">

                               <label class="control-label col-sm-2" for="subject">Subject:</label>
                               <div class="col-sm-10">
                                     <input type="text" class="form-control" id="subject" placeholder="Enter Subject" name="subject" value="">
                               </div>

                         </div>

                         <div class="form-group mb-4">

                               <label class="control-label col-sm-2" for="message">Message:</label>
                               <div class="col-sm-10">
                                     <textarea class="form-control editor" name="message"></textarea>
                               </div>

                         </div>

                         <div class="form-group "> 
                               <div class="col-sm-offset-2 col-sm-10">
                                     <input type="submit" class="btn btn-info" name="submit" value="Submit">
                               </div>
                         </div>

                    </form>

               </div>

          </div>

     </div>

</body>
</html>

5. AJAX – CKEditor file upload

Create ckfileupload.php file for uploading CKEditor file. Also, create uploads folder.

Access the file using upload name.

Check if the file has a valid extension or not. If valid then upload the file to the uploads folder and store some data for return response to CKEditor in $data Array. Pass $filename to $data['fileName'], 1 to $data['uploaded'], and $location to $data['url'].

If file is not uploaded then pass 0 to $data['uploaded'] and an error message to $data['error']['message'].

Return $data Array in JSON format.

Completed Code

<?php

$data = array();
if(isset($_FILES['upload']['name'])){
      // file name
      $filename = $_FILES['upload']['name'];

      // Location
      $location = 'uploads/'.$filename;

      // file extension
      $file_extension = pathinfo($location, PATHINFO_EXTENSION);
      $file_extension = strtolower($file_extension);

      // Valid extensions
      $valid_ext = array("jpg","png","jpeg");

      if(in_array($file_extension,$valid_ext)){ 
            // Upload file
            if(move_uploaded_file($_FILES['upload']['tmp_name'],$location)){

                  $data['fileName'] = $filename;
                  $data['uploaded'] = 1;
                  $data['url'] = $location;
            } 
      }else{
            $data['uploaded'] = 0;
            $data['error']['message'] = 'File not uploaded.'; 
      }

}else{
     $data['uploaded'] = 0;
     $data['error']['message'] = 'File not uploaded.'; 
}

echo json_encode($data);
die;

6. JavaScript

Initialize CKEditor on .editor class. With ckfinder set upload file URL. Specify URL in uploadURL . I set it to ckfileupload.php.

Completed Code

ClassicEditor
    .create( document.querySelector( '.editor' ),{ 
          ckfinder: {
                uploadUrl: "ckfileupload.php",
          }
    } )
    .then( editor => {

          console.log( editor );

    } )
    .catch( error => {
          console.error( error );
    } );

7. Output

View Output


8. Conclusion

To display saved data in the database of CKEditor on the page you just need to directly assign it to the textarea element and initialize the CKEditor. Content will automatically format.

You can also view these tutorials –

If you found this tutorial helpful then don't forget to share.

Leave a Comment