Rizwan Khan
Rizwan Khan

Reputation: 401

How to insert HTML entities in MySQL using CodeIgniter?

I am creating an application using CodeIgniter/MySQL. The problem is that when I store a text with Quotes or Apostrophe. It stores an Blank value to MySQL database.

function add_article($title, $desc){
        $data = array(
            'title' => htmlentities($title, ENT_QUOTES, "UTF-8"),
            'desc' => htmlentities($desc, ENT_QUOTES, "UTF-8")
        );
        if($this->db->insert('articles', $data)){
            return TRUE;
        } else {
            return FALSE;
        }
}

The character set of my table "articles" is "utf8" and COLLATE is utf8_unicode_ci. And HTML character set is also UTF-8. what's wrong? Please help me, and thanks in advance. If i don't use htmlentities() function i face two problems which i mention in my comments below:

Upvotes: 0

Views: 7873

Answers (2)

Valeh Hajiyev
Valeh Hajiyev

Reputation: 3246

Try this:
Add this mysql query in the system/database/DB.php file at the end of DB function. (before return $DB; ) .

$DB->simple_query('SET NAMES \'utf8\'');

Upvotes: 0

Francis Avila
Francis Avila

Reputation: 31631

You could have problems either on input or on output.

On Input

First of all, make sure that the string you receive actually is utf-8.

  • If you received the data from a form, add accept-encoding="utf-8" to the form element.
  • Verify that your input string could be a valid utf-8 stream with TRUE===mb_check_encoding($string, 'UTF-8')
  • Check that the byte sequence is as expected by counting characters: mb_strlen($string, 'UTF-8') should return the same number of characters as what you see, and a number less than strlen($string) (which counts bytes).

In your application/config/database.php, ensure you have these two settings for your database connection:

$db[$dbgroupname]['char_set'] = "utf8";
$db[$dbgroupname]['dbcollat'] = "utf8_unicode_ci";

Replace $dbgroupname with the group name of your connection (e.g., 'default').

Don't use htmlspecialchars or htmlentities on data before you store it. Use those on output, in your views.

On Output

Ensure that whatever you are using to view the data that comes out of your database expects a utf-8 encoding.

For html, make sure your Content-Type header includes charset=utf8 and your html document's head looks like this:

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

Check your results in multiple browsers. Some browsers do charset sniffing and might choose a different charset than what you declare. If so, this means that something on your page is not valid UTF-8--find that thing and eliminate.

If you are using some kind of database viewer (PHPMyAdmin, Navicat, etc), make sure the connection is configured to expect utf-8.

Upvotes: 4

Related Questions