1

I want to set UTF-8 in this file

When I select data from database it's will be like this

**??????????**
<?php
    define("__HOST__", "localhost");
    define("__USER__", "root");
    define("__PASS__", "root");
    define("__BASE__", "db_blog");

    class DB {
        private $con = false;
        private $data = array();

        public function __construct() {
            $this->con = new mysqli(__HOST__, __USER__, __PASS__, __BASE__);
            if(mysqli_connect_errno()) {
                die("DB connection failed:" . mysqli_connect_error());
            }
        }
        public function qryPop() {
            $sql = "SELECT * FROM `tb_blog` ORDER BY `id`" ;

            $qry = $this->con->query($sql); 
            if($qry->num_rows > 0) {
                while($row = $qry->fetch_object()) {
                    $this->data[] = $row;
                }
            } else {
                $this->data[] = null;
            }
            $this->con->close();
        }

?>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Cakkaphong Khangsri
  • 154
  • 1
  • 2
  • 10

2 Answers2

1

You can make use of the set_charset.

PHP

From the documentation page,

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

printf("Initial character set: %s\n", $mysqli->character_set_name());

/* change character set to utf8 */
if (!$mysqli->set_charset("utf8")) {
    printf("Error loading character set utf8: %s\n", $mysqli->error);
    exit();
} else {
    printf("Current character set: %s\n", $mysqli->character_set_name());
}

$mysqli->close();
?>

or you can use header to set the character set too.

header('Content-type: text/plain; charset=utf-8');
Script47
  • 14,230
  • 4
  • 45
  • 66
1

Before executing mysql query, use : $this->con->set_charset("utf8");

Pubudu Jayawardana
  • 2,250
  • 1
  • 13
  • 18