Skip to main content

Save TinyMCE Editor Content with PHP & MySQL

In our previous tutorial, we have explained how to develop Student Attendance System with PHP & MySQL. In this tutorial, we will explain how to use TinyMCE editor to replace textarea to save content with ajax, PHP and MySQL.

TinyMCE is the most advance JavaScript WYSIWYG HTML editor to create contents for websites. The editor can easily be integrated into any website to convert textarea to HTML editor to create HTML contents.

If you’re working on website and wants to replace normal textarea with advanced WYSIWYG HTML editor, then you’re here at the right place.

We will cover the tutorial in easy steps to integrate TinyMCE editor and save contents to MySQL database with ajax and PHP.

Also, read:

So let’s implement TinyMCE Editor with Ajax, PHP and MySQL. The major files are:

  • index.php: PHP file to load TinyMCE editor to save content.
  • tinymce_editor.js: A JavaScript to initiliaze TinyMCE editor.
  • action.php: Action file to handle ajax request.
  • Post.php: A class to hold methods.

Step1: Create MySQL Database Table

First we will create MySQL database table posts to store contents from TinyMCE editor.

CREATE TABLE `posts` (
  `id` int(11) NOT NULL,
  `message` text NOT NULL,
  `user` varchar(255) NOT NULL,
  `edited` int(11) NOT NULL DEFAULT 0,
  `created` datetime NOT NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Step2: Include Bootstrap, jQuery and TinyMCE Editor Files

As we will design pages with Bootstrap, so we will include Bootstrap files. We will also include jQuery and TinyMCE files in index.php file.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="tinymce/tinymce.min.js"></script>
<script src="js/tinymce_editor.js"></script>

Step3: Create Form with TinyMCE Editor

In index.php file, we will create HTML form with textarea and submit button to save form data.

<form id="posts" name="posts" method="post">
	<textarea name="message" id="message"></textarea><br>	
	<input type="hidden" name="action" id="action" value="save" />
	<button type="submit" id="save" name="save" class="btn btn-info saveButton">Save</button>
</form>

Step4: Initialize TinyMCE Editor

In tinymce_editor.js file, we will initialize TinyMCE editor. We will user textarea to convert into advance TinyMCE editor.

tinymce.init({
	selector: "textarea",
	plugins: [
		"code ",
		"paste"
	],
	toolbar: "undo redo | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link code ",
	menubar:false,
    statusbar: false,
	content_style: ".mce-content-body {font-size:15px;font-family:Arial,sans-serif;}",
	height: 200	
});

Step5: Handle Form Submit and Save Content

We will handle form submit with jQuery and make ajax request to action.php with action save to save form values to database table and display saved content on ajax request success.

$(document).on('submit','#posts', function(event){
	var formData = $(this).serialize();
	$.ajax({
			url: "action.php",
			method: "POST",              
			data: formData,
			dataType:"json",
			success: function(data) {     
				var html = $("#postHtml").html();					
				html = html.replace(/USERNAME/g, data.user);
				html = html.replace(/POSTDATE/g, data.post_date);
				html = html.replace(/POSTMESSAGE/g, data.message);
				$("#postLsit").append(html).fadeIn('slow');
				tinymce.get('message').setContent('');
			}
	});		
	return false;
});

In action.php file, we will handle ajax POST request and call method insert() to insert content to the database.

include_once 'config/Database.php';
include_once 'class/Post.php';
$database = new Database();
$db = $database->getConnection();
$post = new Post($db);
if(!empty($_POST['message']) && $_POST['message'] && $_POST['action'] == 'save') {	
	$post->message = $_POST['message'];
	$post->user = "User";
	$post->insert();	
}

We will implement method insert() in class Post.php to save content into MySQL database table and return saved data as JSON response to display content record.

public function insert(){
		
	if($this->message) {

		$stmt = $this->conn->prepare("
			INSERT INTO ".$this->postsTable."(`message`, `user`)
			VALUES(?, ?)");
					
		$stmt->bind_param("ss", $this->message, $this->user);
		
		if($stmt->execute()){	
			$lastPid = $stmt->insert_id;
			$sqlQuery = "
				SELECT id, message, user, DATE_FORMAT(created,'%d %M %Y %H:%i:%s') AS post_date
				FROM ".$this->postsTable." WHERE id = '$lastPid'";
			$stmt2 = $this->conn->prepare($sqlQuery);				
			$stmt2->execute();
			$result = $stmt2->get_result();
			$record = $result->fetch_assoc();
			echo json_encode($record);
		}		
	}
}	

Step6: Display Saved Records

We will display saved records in index.php file by calling getPost() method.

<div id="postLsit">		
<?php
$result = $posts->getPost();
while ($post = $result->fetch_assoc()) {			
	$date = date_create($post['created']);
?>
	<article class="row">
		<div class="col-md-2 col-sm-2 hidden-xs">
		  <figure class="thumbnail">
			<img class="img-responsive" src="images/user-avatar.png" />
			<figcaption class="text-center"><?php echo ucwords($post['user']); ?></figcaption>
		  </figure>
		</div>
		<div class="col-md-10 col-sm-10">
		  <div class="panel panel-default arrow left">
			<div class="panel-body">
			  <header class="text-left">
				<div class="comment-user"><i class="fa fa-user"></i> By: <?php echo $post['user']; ?></div>
				<time class="comment-date" datetime="16-12-2014 01:05"><i class="fa fa-clock-o"></i> <?php echo date_format($date, 'd M Y H:i:s'); ?></time>
			  </header>
			  <div class="comment-post">
				<p>
				<?php echo $post['message']; ?>
				</p>
			  </div>
			  <p class="text-right"><a href="#" class="btn btn-default btn-sm"><i class="fa fa-reply"></i> reply</a></p>
			</div>
		  </div>
		</div>
	</article>		
<?php }	?>
</div>

We will implement method getPost() in class Post.php to get records.

public function getPost(){		
	$sqlQuery = "
		SELECT *
		FROM ".$this->postsTable." ORDER BY id DESC";
	
	$stmt = $this->conn->prepare($sqlQuery);
	$stmt->execute();
	$result = $stmt->get_result();			
	return $result;	
}

You may also like:

You can view the live demo from the Demo link and can download the source from the Download link below.
Demo Download