How to make Mysql return utf-8?

Asked

Viewed 9,952 times

7

When I require information from my database containing special characters I receive " but in the grouping phpmyadmin is "UTF-8" and my website also has the goal of UTF-8 what can I do to return the correct?

  • 2

    Utilize urf8_encode($string) or urf8_decode($string)

  • Thank you very much, I was unaware of that function

  • @Marceloboni Add as question so that I mark the answer pf

4 answers

7


One suggestion is to convert everything enters in the database in html entities, as follows the php code:

$email = addslashes(htmlentities($_POST['email'], ENT_QUOTES,'UTF-8')); 

This way, all the special characters are converted, and when displaying them, the browser itself will interpret it.

It will be converted according to the table available in http://erikasarti.net/html/acentuacao-caracteres-especiais/

á = á (&aacute)

ã = ã (&atilde)

and so on


UPDATE

Another suggestion that would be more appropriate is to create a database in the UTF-8 encoding. You can create the Mysql database already in UTF-8:

CREATE DATABASE `banco` DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;

You can create a table in UTF-8

CREATE TABLE document (
    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    campo VARCHAR(50),
) CHARACTER SET utf8 COLLATE utf8_general_ci;

Remember to set the UTF-8 charset on your HTML pages

<head>
  <meta charset="UTF-8">
</head>

And using the UTF-8 header in PHP files

<?php header("Content-type: text/html; charset=utf-8"); ?>

If it is not yet possible to register accents in the database you can use in PHP

// Para mysqli
 mysqli_set_charset($con,"utf8");

// Para PDO
 $dsn = "mysql:host=localhost;dbname=world;charset=utf8";
 $opcoes = array(
     PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES UTF8'
 );
 $pdo = new PDO($dsn, $usuario, $senha, $opcoes);

Another thing that might help is adding to your . htaccess

AddDefaultCharset utf-8

Remember, "no UTF-8 is too much".

6

I don’t know if it’s ideal, but you can make an appointment that way too

$sql = "SELECT * FROM tbl_produto WHERE nome_produto = :nome_produto collate utf8_unicode_ci ";

5

If you are using PDO add this line:

$pdo -> exec("SET CHARACTER SET utf8");

2

If you are using mysqli, use the mysqli_set_charset($Connection,"utf8") function. This function sets the default character set for sending and receiving data to the Database. If you are using PDO and PHP above version 5.3.6 you can specify the character set in DSN.

$dsn = sprintf("mysql:host=%s;dbname=%s;charset=utf8", $host, $dbname);
                $connection = new \PDO($dsn, $user, $password);

Or (For PHP versions earlier than 5.3.6)

$dsn = sprintf("mysql:host=%s;dbname=%s", $this->host, $this->dbname);
                    $connection = new \PDO($dsn, $this->user, $this->password);
$connection->exec('SET names = utf-8');

Browser other questions tagged

You are not signed in. Login or sign up in order to post.