In this tutorial, We will show you how to use CKEditor 5 in PHP. we can easily install CKEditor 5 and use it. so we will give you a simple example of how to use ckeditor 5 with php.
CKEditor 5 is an Open Source text editor. which is provide lots of features such as Formatting features, Basic text styles, font features, image features, embed media into our content. if you want to know more about CKEditor 5 features then you can visit the CKEditor 5 official site.
In this example, we will use the ckeditor cdn js file and crate form. so we can easily implement the ckeditor 5 in html.
index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>how to use ckeditor 5 in php - XpertPhp</title>
<script src="https://cdn.ckeditor.com/ckeditor5/31.1.0/classic/ckeditor.js"></script>
</head>
<body>
<form method="post" action="add.php">
<textarea name="editor" id="editor" rows="10" cols="80">
This is my textarea to be replaced with CKEditor 5.
</textarea>
<p><input type="submit" name="btnSubmit" value="submit" /></p>
</form>
<script>
ClassicEditor
.create( document.querySelector( '#editor' ) )
.catch( error => {
console.error( error );
} );
</script>
</body>
</html>
Now, we can also use with php. if want to store data into databse then you can see our php example.
<?php
if($_POST['btnSubmit']){
$content = base64encode($_POST['editor']);
// Create connection
$conn = new mysqli("localhost", "root", "", "dbtest");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO post (content) VALUES ('".$content."')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>how to use ckeditor 5 in php - XpertPhp</title>
<script src="https://cdn.ckeditor.com/ckeditor5/31.1.0/classic/ckeditor.js"></script>
</head>
<body>
<form method="post" action="add.php">
<textarea name="editor" id="editor" rows="10" cols="80">
This is my textarea to be replaced with CKEditor 5.
</textarea>
<p><input type="submit" name="btnSubmit" value="submit" /></p>
</form>
<script>
ClassicEditor
.create( document.querySelector( '#editor' ) )
.catch( error => {
console.error( error );
} );
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Read CKEditor data from Database</title>
</head>
<body>
<?php
$mysqli = new mysqli("localhost", "root", "", "dbtest");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli->connect_error;
exit();
}
$sql = "SELECT * FROM post order by id desc limit 1";
echo "<h2>Displaying content from database</h2>";
if ($result = $mysqli->query($sql)) {
$row = $result->fetch_assoc()
$content = base64decode($row['content']);
echo $content;
}
$mysqli->close();
?>
</body>
</html>