'PHP & MySQL - Problems with UTF-8 encode
I have a form with a input that accept UTF-8 characters:
<form method="post" action="faz-personagem.php" accept-charset="UTF-8">
<div class="row">
<label for="nome">Nome</label>
<input type="text" name="nome">
</div>
...
<button type="submit">Enviar</button>
</form>
And a script that send the data to a database:
<?php
header("Content-Type: text/html;charset=UTF-8");
$conexao = mysql_connect('localhost', 'root', 'pass');
mysql_select_db('pan-tactics');
$nome = $_POST['nome'];
$nome = utf8_encode($nome);
$sql = "INSERT INTO personagens VALUES";
$sql .= "('$nome')";
$resultado = mysql_query($sql);
echo 'Personagem criado com sucesso.';
mysql_close($conexao);
?>
I also have specified in the creation of the database the collation utf8_unicode_ci and yet what I get is wrong special characters:
What can I do to fix it?
Solution 1:[1]
Keep in mind that collation is not the same as charset. You need to set your database and table to be in UTF-8 encoding. This can be done with running this SQL command (only need to be done once).
ALTER DATABASE databasename CHARACTER SET utf8 COLLATE utf8_unicode_ci;
ALTER TABLE tablename CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;
Furthermore, you should set the mysql_* connection to UFT-8. This code should be placed directly after connecting to your database.
mysql_set_charset("utf8");
I see you already set the PHP header to UTF-8 as well, so that's good.
Keep in mind that usage of mysql_* functions are deprecated and no longer maintained; you should switch to PDO or MySQLi for security reasons.
If neither of these steps helped you, you may need to save the document itself as UTF-8 w/o BOM, this can be done in Notepad++ as Format -> Convert to UFT-8 w/o BOM.
Solution 2:[2]
i had the same problem.
This was my solution:
$con = mysqli_connect('localhost', 'secretuser', 'secret', 'mydb');
mysqli_set_charset($con, "utf8mb4");
in your case:
$conexao = mysql_connect('localhost', 'root', 'pass');
mysqli_set_charset($conexao, "utf8mb4");
Maybe this will help someone who comes across this old post.
Solution 3:[3]
Set your connection with the database to utf-8: mysql_set_charsethttp://php.net/manual/en/function.mysql-set-charset.php
U should use mysqli_ functions or PDP rather then mysql_ functions!
Solution 4:[4]
Check your collation of your database (including columns and tables).
Also, try adding mysql_query("set names 'utf8'"); after the connection to database in your code.
Solution 5:[5]
Were you expecting João for the first name? If so, you have "Mojibake".
João is even worse -- It looks like you Mojibaked João to get João, then Mojibaked that to get João.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Qirel |
| Solution 2 | Markus Weiß |
| Solution 3 | Frank B |
| Solution 4 | destraaaa |
| Solution 5 | Rick James |

