Seo woo
Seo woo

Reputation: 11

php utf8 encoding doesn't work

I setted utf8 encoding in php but in Mariadb crashed letter appeared in db:

MariaDB variables

This is MariaDB 10.1 I also setted database like create database databasename character set utf8 collate utf8_general_ci:

MariaDB 10.1 database

and this is source code:

<?php
header('Content-Type: text/html; charset=utf-8');

function db_connect(){

$db_user = "kskim";
$db_pass = "123456";
$db_host = "localhost";
$db_name = "test";
$db_type = "mysql";
$dsn = "$db_type:host=$db_host;dbname=$db_name;charset=utf8";
try{
//        $conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
////        mysqli_query($conn,"set names utf-8");
//        mysqli_set_charset($conn, "utf8");
    $pdo = new PDO($dsn,$db_user,$db_pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);
    print "데이터베이스에 접속하였습니다.";
} catch (PDOException $Exception) {
    die('오류 : '.$Exception->getMessage());
}

return $pdo;
}

?>

<?php
header('Content-Type: text/html; charset=utf-8');

$id=$_REQUEST["id"];
$passwd = $_REQUEST["passwd"];
$name = $_REQUEST["name"];
$tel = $_REQUEST["tel"];

require_once 'MYDB.php';
$pdo = db_connect();

try{
    $pdo->beginTransaction();
    $sql = "insert into member2(id,passwd,name,tel,reg_date)"
            . "values(?,?,?,?,now())";
    $stmh=$pdo->prepare($sql);
    $stmh->bindValue(1, $id, PDO::PARAM_STR);
    $stmh->bindValue(2, $passwd, PDO::PARAM_STR);
    $stmh->bindValue(3, $name, PDO::PARAM_STR);
    $stmh->bindValue(4, $tel, PDO::PARAM_STR);
    $stmh->execute();
    $pdo->commit();
    print "데이터가 추가되었습니다.";
    //echo mysqli_character_set_name($conn);
    print "$id $passwd $tel $name";

} catch (PDOException $Exception) {
    $pdo->rollBack();
    print "오류 :".$Exception->getMessage();

}

    ?>

I setted UTF-8 setting in my.ini like

character-set-server=utf8
skip-character-set-client-handshake
collation-server = utf_unicode_ci
init-connect='SET NAMES utf8'

When I add this paragraph in my.ini crashed letter? Changed to like ? what should i do??

Upvotes: 1

Views: 407

Answers (1)

Mehrdad Dashti
Mehrdad Dashti

Reputation: 124

You can use this code.

$servername="localhost";
$username="";
$password="";
$dbname="";
$dsn="mysql:host=$servername;dbname=$dbname";
try{
$connect=new PDO ($dsn,$username,$password);
$connect->exec("SET NAMES 'utf8';");
}catch(PDOException $error){
      echo "Error in connect".$error->getMessage();
      exit();
}

Upvotes: 1

Related Questions