Advertisement
econz

Caso UTF-8 com PHP e MySQL

Apr 5th, 2017
234
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. 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:
  2.  
  3. CREATE DATABASE
  4. baza_danni
  5.  
  6. DEFAULT CHARACTER SET
  7. utf8
  8.  
  9. DEFAULT COLLATE
  10. utf8_general_ci
  11.  
  12. 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:
  13.  
  14. CREATE TABLE tablica ( ... ) CHARACTER SET utf8 COLLATE utf8_general_ci;
  15.  
  16.  
  17. The same is for table columns ot type CHAR, VARCHAR and TEXT. This affects directly stored text:
  18.  
  19. CREATE TABLE tablica
  20. (
  21. kolona1 TEXT CHARACTER SET utf8 COLLATE utf8_general_ci
  22. );
  23.  
  24.  
  25. 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:
  26.  
  27. $mysql_link = mysql_connect($host, $username, $password);
  28. mysql_select_db($database, $mysql_link); mysql_query('SET character_set_results=utf8');
  29. mysql_query('SET names=utf8');
  30. mysql_query('SET character_set_client=utf8');
  31. mysql_query('SET character_set_connection=utf8');
  32. mysql_query('SET character_set_results=utf8');
  33. mysql_query('SET collation_connection=utf8_general_ci');
  34.  
  35. PHP is set up. Now add thi META tag to your page to inform the browser that your page is UTF-8 encoded:
  36.  
  37. <html>
  38. <head>
  39. <title>Title</title>
  40. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  41. </head>
  42. <body>
  43.  
  44. </body>
  45. </html>
  46.  
  47. It is good also to add HTTP header through PHP header() function:
  48.  
  49. header("Content-Type:text/html; charset=utf-8");
  50.  
  51. You must change your text editorsettings, so that it saves all files in UTF-8 format .
  52.  
  53. 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!
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement