Tuesday, May 22, 2012

php-mysql-unicode-solution


Step One: SET THE CHARSET TO UTF-8 IN THE HEAD SECTION
First of all, the browser needs to know that you are going to display or use Unicode in this page. So, go to your <HEAD></HEAD> section and set the charset to utf-8. So, the browser will be able to show the Unicode text without any error and smoothly. You can also copy and paste the line below
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
Step Two: CREATING THE DATABASE


When you create your (a) Database and (b) any Table in the database, set the Collation of both of them to utf8_unicode_ci and you know it is very easy if you are using phpMyAdmin.




Step Three: DATABASE INITIALIZATION


When you initialize the database connection, please add the “extra lines”



<?php

 define('HOSTNAME', 'localhost');
 define('USERNAME', 'database_user_name');
 define('PASSWORD', 'database_password');
 define('DATABASE', 'database_name');

 $dbLink = mysql_connect(HOSTNAME, USERNAME, PASSWORD);
 mysql_query("SET character_set_results=utf8", $dbLink);
 mb_language('uni');
 mb_internal_encoding('UTF-8');
 mysql_select_db(DATABASE, $dbLink);
 mysql_query("set names 'utf8'",$dbLink);

?>
But why are you adding the extra lines? Because you are letting the 
database know what kind of input you are going to work with soon.


Step Four: INSERTING INPUTS/DATA IN THE DATABASE



<?php

 mysql_query("SET character_set_client=utf8", $dbLink);
 mysql_query("SET character_set_connection=utf8", $dbLink);

 $sql_query = "INSERT INTO
 TABLE_NAME(field_name_one, field_name_two)
 VALUES('field_value_one', 'field_value_two')";
 mysql_query($sql_query, $dbLink);

?>
Why are you adding the first two lines for? Because the database should know what kind of data is going to be stored.



Step Five: UPDATING INPUTS/DATA IN THE DATABASE



<?php

 mysql_query("SET character_set_client=utf8", $dbLink);
 mysql_query("SET character_set_connection=utf8", $dbLink);

 $sql_query = "UPDATE TABLE_NAME
 SET field_name_one='field_value_one', field_name_two='field_value_two'
 WHERE id='$id'; ";
 mysql_query($sql_query, $dbLink);

?>
So, you are adding the extra two lines before you run your query string as you are playing with Unicode.


Step Six: SEARCHING DATA FROM THE DATABASE



<?php

 mysql_query("SET character_set_results=utf8", $dbLink);

 $sql_query = "SELECT * FROM TABLE_NAME WHERE id='$id'; ";
 $dbResult = mysql_query( $sql_query, $dbLink);

?>
Adding the one extra line every time you search your Unicode data is enough.


OKKK.

You are done. This should work smoothly for handling your data in any 
language does not matter it is Bangla (my mother tongue), Hindi, 
Chinese, French, German, Spanish, Russian, Arabian (Arabic), Urdu,  or 
any other language.


And do not forget to leave a comment if you have any. Because I need to update the post in case required.


Thanks for reading and please check if it works for you.

No comments:

Post a Comment