Include UTF-8 charset in mysqli connection

6
Hello, after repairing my code is full of strange characters like ???, I tried to fix it but I discovered that I need to change the charset through the mysqli connection, but the problem is that I do not know how to do this! Can anyone help me?

Here is my mysqli connection code

config.php

<?php

//site specific configuration declartion
define( 'BASE_PATH', 'http://localhost/user_login/');
define( 'DB_HOST', 'localhost' );
define( 'DB_USERNAME', 'root');
define( 'DB_PASSWORD', '');
define( 'DB_NAME', 'login');

function __autoload($class)
{
    $parts = explode('_', $class);
    $path = implode(DIRECTORY_SEPARATOR,$parts);
    require_once $path . '.php';
}

?>

DBclass

<?php

    class Cl_DBclass
    {
    /**
     * @var $con vai realizar conexão com o banco
     */
    public $con;

    /**
     * Isto irá criar uma conexão de banco de dados
     */
    public function __construct()
    {
        $this->con = mysqli_connect(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
        if( mysqli_connect_error()) echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }
    }
?>

Thanks in advance!

    
asked by anonymous 30.07.2015 / 20:37

4 answers

6

After connecting to the database, call set_charset to change the charset. Use character_set_name () to know the current charset.

$this->con = mysqli_connect(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
$this->con->set_charset("utf8");
    
30.07.2015 / 20:45
6

Using this form with mysql:

You can change your builder to:

public function __construct()
{
    $this->con = mysqli_connect(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
    if(mysqli_connect_error()) { // < evite IF sem chaves
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    } else {
        mysqli_query("SET NAMES 'utf8'");
        mysqli_query('SET character_set_connection=utf8');
        mysqli_query('SET character_set_client=utf8');
        mysqli_query('SET character_set_results=utf8');
    }
}

Returns all queries seamlessly in the encoding.

    
30.07.2015 / 20:41
2

In my connection, I put the charset below out of php:

<meta charset="utf-8">

Inside the php I put it like this:

$con->set_charset("utf8");

My html pages with "charset utf-8" and in the database I put collate "utf8_general_ci" . Okay, that's the problem.

    
08.06.2017 / 04:41
1

Ok, Problem Solved! At first, the solutions given here were not working because I had included this code in an earlier attempt to arrange:

<?php
    header('Content-Type: text/html; charset=UTF-8');
?>

Then I used one of the given solutions, (both work) exclude it and I changed the value of meta tag charset from utf-8 to iso-8859-1 ! Thank you all!

    
31.07.2015 / 03:31