0

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";
?>
1
  • 3
    If you just did a google query on php mysqli utf8 you would have wound the answer in the first result. Commented Apr 14, 2013 at 17:34

5 Answers 5

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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');

Comments

1

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 :)

Comments

0

Try setting the charset before your query.

Comments

0

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');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.