使用mysqli保存来自contentEditable div的数据

使用mysqli保存来自contentEditable div的数据

问题描述:

I'm trying to save data from contentEditable div to mySql DB. But it seems that '+' symbol cannot be stored in DB. Is this right concept or am I missing something?

index.php

<div id="la_sent" contentEditable=true></div>
<button class="saveChanges">Save changes</button>

script.js

$(document).ready(function(){
  $( ".saveChanges" ).click(function() {
      content = $('#la_sent').html();
      dataUrl = "iid=1&content="+content;
      $.ajax({
        url:"ajax.php",
        type:"POST",
        data:dataUrl,
        success:function(data){
            ...
      }});
  }); 
}); 

ajax.php

$type = $_POST['iid'];
$content = $_POST['content'];
$mysqli=connect_database(); //connection to database
$stmt = $mysqli->prepare('UPDATE email_structure SET content = ? WHERE type = ?');
$stmt->bind_param('ss', $content, $type);
$ress = $stmt->execute();
$stmt->close();
$mysqli->close();
echo "OK";

For example: If I write in div element string 'a+b+c' it adds in DB string 'a b c '. Any idea why?

Plus signs get replaced as spaces by default so you have to encode them first.

encodeUriComponent is one way to do it in javascript

So editing your script.js to pass content variable through encodeURIComponent before appending it to datUrl should do the trick.

$(document).ready(function(){
  $( ".saveChanges" ).click(function() {
      content = $('#la_sent').html();
      dataUrl = "iid=1&content="+encodeURIComponent(content);  //encode content variable
      $.ajax({
        url:"ajax.php",
        type:"POST",
        data:dataUrl,
        success:function(data){
            ...
      }});
  }); 
}); 

For security purposes, you should ALWAYS escape your text, before you plug it into your database (search with, store, etc.) See php's mysqli_real_escape_string to do this. Even though you are using prepared statements, you should still escape your characters.

If it's really a problem, you could replace the + with another character and, then replace it back when you are retrieving from the DB