1

I am having a problem inserting text into a mysql database with jquery and php. I have a jquery script that uses .ajax to pass parameters to a php page that does the insert. The result is text in my database that looks like this " CC". I want it to be "* CC". I know this probably has to do with UTF-8 encoding but I can't figure it how to fix it. My DB tables are "utf8_unicode_ci". Can someone tell me what I am doing wrong please?

My .ajax code is...

var comment = "* CC";
$.ajax({
    url: "php/add_riw_report.php",
    type: "post",
    dataType: "json",
    data: { comment: comment  },
});

And in firebug the POST source is...

&grade=*%C2%A0CC

I have this at the top of my php page...

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

And the insert php code is...

$sql = "INSERT INTO 
        riw_events  
    VALUES(
        mysql_real_escape_string($_POST["comment"])."'
    )";
$rs=$db->query($sql);
2
  • Dont use mysql , go for mysqli or pdo sql Commented Jan 29, 2015 at 18:35
  • 1
    WARNING: mysql_query is an obsolete interface and should not be used in new applications as it's being removed in future versions of PHP. A modern replacement like PDO is not hard to learn. If you're new to PHP, a guide like PHP The Right Way can help explain best practices. Commented Jan 29, 2015 at 18:54

1 Answer 1

5

PDO object must be configured to use utf8 charset

$db = new PDO("mysql:host=localhost;dbname=DB;charset=UTF8");

For Mysqli http://php.net/manual/en/mysqli.set-charset.php

$db->set_charset('utf8');
Sign up to request clarification or add additional context in comments.

3 Comments

I'm not using PDO...I'm using MySQLi. Should I do the same with that?
If you're using mysqli, there's absolutely no reason to be using mysql_real_escape_string, that thing is dangerous. Use using prepared statements and bind_param to add user data to your query.
switched to PDO and removed old mysql_real_escape_string. thanks, it is working! looking at prepared statements now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.