econz icon

Caso UTF-8 com PHP e MySQL

econz | PRO | 04/05/17 04:39:35 PM UTC | 0 ⭐ | 714 👁️ | Never ⏰ | []
text |

1.88 KB

|

None

|

0 👍

/

0 👎

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 DATABASE 
baza_danni
     DEFAULT CHARACTER SET 
utf8
     DEFAULT COLLATE 
utf8_general_ci
 If 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:
 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