title: Escaping single quotes in PHP/MySQL insert not working
body: <p>I'm trying to insert a string into a MySQL table using a combination of JavaScript/Ajax and PHP. After passing the desired (JavaScript) string to a PHP script using Ajax, I then attempt to insert it into a table using PHP. </p>
  
  <p>The PHP script is working, however as soon as a single quote (') is encountered the insertion stops at that point. I have tried using mysql_real_escape_string(), addslashes(), htmlentities() and str_replace() in various combinations, trying this with magic quotes on and off and no matter what, the single quotes cannot be handled. I would just like to either preserve them or have them escaped properly but nothing is working for me - the string itself is from a Tweet so I'm wondering if perhaps some encoding conflict is causing this? Any advice as to how to overcome this would be greatly appreciated.</p>
  
  <p>For example, to better illustrate, if I pass this string to the PHP script:</p>
  
  <p>promise me you won't vote</p>
  
  <p>Then after sanitizing the string with any of the methods above and inserting into the MySQL table, it will always appear like so, in the MySQL table:</p>
  
  <p>promise me you won</p>
  
  <p>Here is my php code:</p>
  
  <pre><code>include("dbconnect.php"); //connect to DB
  $tweet = mysql_real_escape_string($_POST['tweet']); //escape the string
  
  if($tweet != '') { //check it's not empty
  
  $query = "insert into Tory (Content) values('$tweet')"; //insert statement
  
  $link = mysql_query($query);
  if (!$link) {
    echo "3";
    die($result);
  }
  echo "&lt;p&gt;".$tweet."&lt;/p&gt;"; //for Ajax callback
  }
  </code></pre>
  
  <p>Here is the Javascript/Ajax code:</p>
  
  <pre><code>$.ajax({  
      type: 'POST',  
      url: 'buildTable.php', //previous php code
      data: "tweet=" + content, //content is the tweet string as javascript var
      success: function(thetweet) {
           $(document.body).append(thetweet);
      }
  });
  </code></pre>
  
  <p>EDIT: Thank you for all the comments and advice offered. A temporary solution I've used is to replace all instances of a single quote with a backslash on the client side, before passing the string to the PHP script. Then switch it back to a single quote when retrieving in either PHP or JavaScript. </p>