How to edit HTML in a WYSIWYG editor (TinyMCE) and save in the database?

1

I currently have a blog about programming created by me and I'm using the TinyMCE editor to create the content. I specifically use TinyMCE because it has a free plugin for image upload, which makes it much easier to create postings with images, the only problem is that sometimes I need to publish in the post content a sample HTML snippet and when saving the POST all looks fine, but at the time of editing the thing goes, TinyMCE understands the example HTML as "truth" HTML and ends up showing the rendered content, not the code.

    
asked by anonymous 15.02.2016 / 14:35

1 answer

4

The TinyMCE editor before being a rich text editor is a normal form, so if you want to edit you should convert < and > to &lt; and &gt; , as in the example: / p>

<!DOCTYPE html>
<html>
<head>
  <script src="http://cdn.tinymce.com/4/tinymce.min.js"></script><script>tinymce.init({selector:'#texto'});</script></head><body><?php$mysqli=newmysqli("localhost", "my_user", "my_password", "world");

$query = 'SELECT postagem FROM tabela WHERE id=1';

if ($result = $mysqli->query($query)) {
    if($row = $result->fetch_assoc()) {
        $variavelDoBanco = $row["postagem"];
    }
}
?>

  <form method="POST" action="arquivo.php">
  <textarea id="texto" name="texto"><?php echo htmlspecialchars($variavelDoBanco); ?></textarea>
  <br>
  <button type="submit">Salvar</button>
  </form>
</body>
</html>
Note that if you use Laravel with Blade, you do not need to use htmlspecialchars , since {$var} already encodes, here is an example:

  • Controller:

    <?php
    namespace App\Http\Controllers;
    
    use App\Http\Controllers\Controller;
    
    class HomeController extends Controller
    {
        public function editar()
        {
            return view('editor', [ 'postagem' => '<b>foo</b> bar <s>baz</s>' ]);
        }
    }
    
  • Template editor.blade.php:

      <form method="POST" action="/editar">
      <textarea id="texto" name="texto">{$postagem}</textarea>
      <br>
      <button type="submit">Salvar</button>
      </form>
    
  

Note being PHP I used the API mysqli the old api mysql_ is discontinued and has been removed in PHP7

     

Old API documentation reporting this:

     

Useful links:

     
    
15.02.2016 / 15:14