Question

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.

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.

For example, to better illustrate, if I pass this string to the PHP script:

promise me you won't vote

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:

promise me you won

Here is my php 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 "<p>".$tweet."</p>"; //for Ajax callback
}

Here is the Javascript/Ajax 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);
    }
});

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.

No correct solution

OTHER TIPS

Insert string with single quote(') or double quote(") in mysql

Just Use addslashes(); in Insertion and stripslashes(); for fetch data.

$str = "Hello Friend's.. Hows you all"s.";
// Outputs: Hello Friend\'s..Hows you all\"s.
echo addslashes($str);

stripslashes — Un-quote string quoted with addslashes(). Returns a string with backslashes stripped off. (\' becomes ' and so on.) Double backslashes (\\) are made into a single backslash (\).

$str = "Hello Friend\'s.. Hows you all"s."; // Outputs: Hello Friend's.. Hows you all"s.
echo stripslashes($str);

Now we come to the point. If we insert string into database with single or double quote like this:

$str = “Hello Friend's.. Hows you all"s.”;
$query = “INSERT INTO tbl (description) VALUES (‘$str’)”;

This will occur error, but if we use addslashes($str) function like below and then insert into database, then no error will be occurred.

$str = “Hello Friend's.. Hows you all"s.”;
$desc_str = addslashes($str);
$query = “INSERT INTO tbl (description) VALUES (‘$desc_str’)”;

similarly we can use stripslashes($str) to print that table field value like this:

echo stripslashes($str);

You can easily avoid the whole escaping thing if you use mysqli or PDO with prepared statements. The mysql_* functions are deprecated anyway, so this would be the perfect opportunity to switch.

Your code would be something like (PDO, using your code):

$query = "insert into Tory (Content) values (:tweet)";
$stmt = $db->prepare($sql);    // $db being your PDO object
$stmt->execute(array(':tweet' => $_POST['tweet']));    // assuming you are not verifying the tweet somewhere else

Replace:

$link = mysql_query($query);
if (!$link) {
  echo "3";
  die($result);
}

With:

mysql_query($query);
if(mysql_errno() != 0)
  die(mysql_error());

I'm not sure if this is relevant and i know it's a little late, but i've just been experiencing a similar problem when trying to create a CSV file. I could not understand why my single quotes were not being escaped.

SOLUTION

Turns out the single quotes in my sring were smart quotes i.e. curly quotes not straight quotes.

After running the function below (Thanks to Chris Shiflett), my quotes were converted and my escaping issues resolved.

Pass each field/cell value/column value to be stored through this function to convert smart characters like curly quotes and emdashs to HTML entities like straight quotes and hyphens

$smart_string = "String containing smart quotes";
$safe_string = convert_smart_quotes($smart_string);

function convert_smart_quotes($string) 
{ 
    $search = array(chr(145), 
                    chr(146), 
                    chr(147), 
                    chr(148), 
                    chr(151)); 

    $replace = array("'", 
                     "'", 
                     '"', 
                     '"', 
                     '-'); 

    //return string with smart characters replaced by html safe characters
    return str_replace($search, $replace, $string); 
}

Like i said, not sure if this will directly help your issue, but might aid you and others in future!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top