After many attempts I couldn't get data from my database in a correct encoding (UTF-8) format.
This is my connection(config.php) file:
<?php
define("DB_HOST", "localhost");
define("DB_USER", "user");
define("DB_PASSWORD", "");
define("DB_DATABASE", "db");
$dbcon = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
?>
My php form for retriving data:
<?php
include('config.php');
$sqlget="SELECT * FROM table";
$sqldata= mysqli_query($dbcon, $sqlget) or die ('error');
mysqli_set_charset('utf8');
echo"<table>";
echo"</table";
?>
You're not sending the link identifier mysqli_set_charset($dbcon , "utf8");
from php manual:
bool mysqli_set_charset ( mysqli $link , string $charset )
And set it before you execute the query.
setting encoding after SELECT is a bit late
set it before running any query
<?php
define("DB_HOST", "localhost");
define("DB_USER", "user");
define("DB_PASSWORD", "");
define("DB_DATABASE", "db");
$dbcon = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
mysqli_set_charset('utf8');
The simplest way of achieving that is running any of these:
// for procedural MySQL (obsolete in PHP 5.4/5.5!)
mysql_query("SET NAMES 'utf8';", $link);
// for procedural MySQLi
mysqli_query("SET NAMES 'utf8';", $link);
// for MySQLi, function notation
mysqli_set_charset($link, "utf8");
// for MySQLi, method notation
$mysqli->set_charset("utf8");
// for PDO
$pdo = new \PDO("mysql:host={$host};dbname={$database};charset=utf8", $user, $password);
That will guarantee the retrieved data will be returned with UTF-8 encoding.
Hope that helps :)
尝试在查询之前设置字符集。
Order is important. You need to set connection encoding before you start executing queries, otherwise it's just too late:
mysqli_set_charset('utf8');
shall be executed just after you connect:
<?php
define("DB_HOST", "localhost");
define("DB_USER", "user");
define("DB_PASSWORD", "");
define("DB_DATABASE", "db");
$dbcon = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
mysqli_set_charset('utf8');
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.