简体   繁体   中英

utf-8 character set not working in php file

Im trying to insert 汉语/漢語 characters into my database but im only getting ????? when i do. Iv look at loads of information on line but no solution works. When i run an insert query in my db with the characters 汉语/漢語 it works, so I know my db is set-up for utf8...Its somthing im doing in my PHP file that's the problem...any help would be greatly appreciated.

<?php
include 'config.php';  
header('Content-Type:text/html; charset=UTF-8');
mysqli_query("SET NAMES utf8");
mysqli_set_charset('utf8');


// check for required fields
if (isset($_POST['name'])) {
$name = mysqli_real_escape_string($link, $_POST['name']);

$result = mysqli_query($link, "INSERT INTO scores(`id` , `name`)VALUES(NULL, '$name'");

You need to make sure your database is operating in UTF-8 mode. You need to do this on the table itself. You said you INSERTED the string, but did you check to see if you can read it back out? As noted in my comment below, you should be sure that you're connecting to MySQL with UTF-8 enabled. There is more information in the answer below:

How to make MySQL handle UTF-8 properly

Additionally, be sure that the PHP file itself is being saved in UTF-8 format. Last but not least ensure the HTML page is correctly set to use utf-8:

<meta charset="utf-8"> vs <meta http-equiv="Content-Type">

Here's an old cheat sheet I rely on. Keep mind that some of this info is out of date

header('Content-Type: text/html; charset=utf-8');
mb_internal_encoding('UTF-8');
mb_http_output('UTF-8');

// only for legacy MySQL_query

mysql_set_charset('utf8',$con);

// only for MySQLi

$mysqli->set_charset("utf8")

also check out: http://tympanus.net/codrops/2009/08/31/solving-php-mysql-utf-8-issues/

PHP didn't use to be natively UTF-8 friendly, you had to rely on secondary functions like these below. I'm pretty sure all of the functions on the left have become UTF-8 friendly for a few years now.

mail()                -> mb_send_mail()
strlen()              -> mb_strlen()   
strpos()              -> mb_strpos()
strrpos()             -> mb_strrpos()
substr()              -> mb_substr()
strtolower()          -> mb_strtolower()
strtoupper()          -> mb_strtoupper()
substr_count()        -> mb_substr_count()
htmlentities($var)    -> htmlentities($var, ENT_QUOTES, 'UTF-8')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM