How to build an UTF-8 website with PHP and MySQL
Let's start with database creation. If you don't want to have difficulties with export/import operations, it is best to make it right. Here's a sample script:CREATE DATABASEIf database is ceated this way, options character_set and collation will be used implicitly for every table within it. But it is a good practice to them explicitly:baza_danni
DEFAULT CHARACTER SETutf8
DEFAULT COLLATEutf8_general_ci
CREATE TABLE tablica ( ... ) CHARACTER SET utf8 COLLATE utf8_general_ci;
The same is for table columns ot type CHAR, VARCHAR and TEXT. This affects directly stored text:
CREATE TABLE tablica
(
kolona1 TEXT CHARACTER SET utf8 COLLATE utf8_general_ci
);
Database setup is ready. Now we should set the PHP database client to provide and extract stored data in the correct format. This should be done right after calling myqsl_connect() function:
$mysql_link = mysql_connect($host, $username, $password);
mysql_select_db($database, $mysql_link); mysql_query('SET character_set_results=utf8');
mysql_query('SET names=utf8');
mysql_query('SET character_set_client=utf8');
mysql_query('SET character_set_connection=utf8');
mysql_query('SET character_set_results=utf8');
mysql_query('SET collation_connection=utf8_general_ci');
PHP is set up. Now add thi META tag to your page to inform the browser that your page is UTF-8 encoded:
<html>
<head>
<title>Title</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
</body>
</html>
It is good also to add HTTP header through PHP header() function:
header("Content-Type:text/html; charset=utf-8");
You must change your text editorsettings, so that it saves all files in UTF-8 format .
That's it. Now you can develop you site and be sure that it will look the same way on most of the browsers is any country and region. Happy coding!
Comments:
edo navon (20-02-2009 18:35) :
Thank for the help.
it was a quick one!em (31-03-2012 06:11) :
thanks
mikey (08-05-2012 17:51) :
Thanks for this article. Cheers.cobra (17-11-2012 08:15) :
Clear, nice and usefull article, thanksСтоян Деков (22-08-2013 01:00) :
Благодаря. Буквално стана утре докато разбера какъв е проблема. Мерси
This page was last modified on 2024-10-04 04:10:21