Ever wished for a text editor that’s more than just basic? Well, meet CKEditor 5, a tool that goes beyond the ordinary. Packed with features to enhance your writing journey, it’s not your average text box.
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.
Table of Content
- Create a Table
- Create a Database connection file
- Download and Include CKEditor 5
- HTML & PHP: Creating the Layout and Saving Data
- Creating AJAX File for Uploading CKEditor Files
- JavaScript: Initializing CKEditor 5 and Setting Upload Path
- Output
- Conclusion
1. Create a Table
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. Create a Database connection file
Create a config.php
for database configuration.
<?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 CKEditor 5
- 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: Creating the Layout and Saving Data
HTML
Create a <form method="post" action="" >
. Within the form, include a text input for the subject, a textarea for the message content, and a submit button.
PHP
If the form is submitted, then reads the POST values and assigns them to respective variables. Check if both the subject and message variables are not empty. If they’re not empty, a new record is inserted into the messages
table. If successful, the page is redirected to the index.php
.
<?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. Creating AJAX File for Uploading CKEditor Files
Create the ckfileupload.php
file responsible for handling AJAX-based file uploads for CKEditor. Also, create upload
folder where the uploaded files will be stored.
Access the file using upload
name – $_FILES['upload']
.
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.
<?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: Initializing CKEditor 5 and Setting Upload Path
Initialize CKEditor 5 on .editor
class. With ckfinder
set upload file URL. Specify the upload URL using the uploadUrl
property. I set it to ckfileupload.php
.
ClassicEditor .create( document.querySelector( '.editor' ),{ ckfinder: { uploadUrl: "ckfileupload.php", } } ) .then( editor => { console.log( editor ); } ) .catch( error => { console.error( error ); } );
7. Output
8. Conclusion
We’ve successfully created a seamless integration between CKEditor 5 and a MySQL database using PHP. By following the steps outlined in this tutorial, you can easily empower users to input, format, and save rich content directly from their browsers.
Remember, to display saved data on the page, you can directly assign it to the textarea element and initialize CKEditor; the content will be automatically formatted.
You can also view these tutorials –
- Save CKEditor 5 data to MySQL database in CodeIgniter 4
- Add CKEditor 5 and save it to MySQL database in Laravel