-1

I've done a very few web PHP/MySQL based web projects, and sooner or later, I always have charset issues.

I live in Spain, and we have some special characters over here: ç ñ á é í ó and ú

There are so many variables, that the charset always gets messed up:

  • MySQL database collation
  • PHP/HTML headers
  • Web browser codification settings
  • PHP settings
  • Apache settings

What I would like to have is a basic guideline on how to setup everything, so that I don't have issues with these Spanish characters.

There are three types of ways I populate my HTML output:

  • I query the MySQL database with PHP, and echo the output.
  • I write some words directly with HTML, for example

    <p>Qué rábanos pasaría mañana</p>
    
  • I read a labels.ini file with parse_ini_file($file); The label file looks something like:

    SORTING_ENTITY = Línea de negocio SORTING_PLURAL = Líneas de negocio MAIN_ENTITY = Instalación MAIN_PLURAL = Instalaciones

So when I view the website, sometimes the texts generated from MySQL are messed up, other times the direct HTML is messed up, and other times everything is okay, but the content coming from the .ini file is messed up.

Also sometimes, I use web forms, so that the users input data that is saved in MySQL. The users write for example "Pájaro" in the web form, and some incorrect chars are stored in the database like "P}jaros" or something like that.

I would like to have some guidelines, so that everything is setup in a way that whatever I write in direct HTML or .ini file is shown in the website, and whatever the users writes in the web form is stored correctly, and also displayed in the same way when later reading this data and echoing with PHP.

I don't want to be using stuff like:

&aacute;
&ntilde;
echo  utf8_encode($dat);  
halfer
  • 19,824
  • 17
  • 99
  • 186
Jack Casas
  • 914
  • 18
  • 37
  • Use the marked dup as a checklist for your project. Today I just fixed a similar issue - pages are UTF8, database and tables are UTF8, but connection needed UTF8 configuration just after logging on to the database. – halfer May 23 '15 at 20:16

1 Answers1

0

In HTML head element always include

<meta charset="UTF-8"/> 

To output UTF-8 charecters in PHP

header("Content-type: 'text/html'; Charset='UTF-8');

Also, remember to put headers on top of every PHP script

For PHP CRUD(Create, Read, Update, Delete) use this code

$conObj = new mysqli("", "", "", "");
    $conObj->query("SET character_set_results = 'utf8', character_set_client = 'utf8', character_set_connection = 'utf8', character_set_database = 'utf8', character_set_server = 'utf8'");

Try to create a class with this "query" function (call it encoder or anything you like), so whenever you make an object of this class, this function will be automatically executed and you will not have to hard code it and write under every connection instance/object.

David Demetradze
  • 1,361
  • 2
  • 12
  • 18