Search code examples
phpmysqlrich-text-editor

How to preserve formatting of text while storing data in mysql database using php?


I'm using HTML5 text editor, using which people can

  1. Make text bold/italics.
  2. Insert link/image.
  3. Change text color, add bullet/numbers etc.

How do I store and retrieve this data in/from mysql database so that the formatting is preserved? Currently, the text is getting stored, but as plain text.

What approach should I adopt to fix this issue?


Solution

  • Use htmlentities() function and in MySQL use TEXT as field type of the attribute

    let the element has id editor then in js use

    $('#editor').html();

    Example:

    <div id="editor">
      <!--Here goes your content from HTML5 Editor-->
    </div>
    

    so use AJAX to save it:

    function StoreText() {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                if (xmlhttp.responseText == "true") {
                    //success message
                } else {
                    //error message
                }
            }
        }
        xmlhttp.open("POST", "Update.php", true);
        xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xmlhttp.send("value=" + $('#editor').html());
    }