php utf8编码不起作用

时间:2018-03-10 04:14:57

标签: php encoding

我在php中设置了utf8编码,但在Mariadb崩溃的信中出现了db:

MariaDB variables

这是MariaDB 10.1我还设置了数据库,如create database databasename 字符集utf8 collat​​e utf8_general_ci:

MariaDB 10.1 database

这是源代码:

<?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();

}

    ?>

我在my.ini中设置了UTF-8设置,如

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

当我在my.in崩溃的信件中添加此段落时?改为喜欢?   我该怎么办?

1 个答案:

答案 0 :(得分:1)

您可以使用此代码。

$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();
}