PHP向MySQL插入记录时中文乱码问题

用的工具是PhpStorm+wampserver中php7.3.5+本地安装的MySQL5.7

Navicat for MySql 新建数据库时编码格式设置成:utf8 -- UTF-8 Unicode 排序规则:utf8_general_ci

先来看看乱码吧!

lm1.png

下面来看源码

<?php
header("Content-Type:text/html;charset=utf-8");
    $host="localhost";
    $user="root";
    $password="zzjava";
    $dbname="community";
    //创建连接
    $conn=new mysqli($host,$user,$password,$dbname);
    if ($conn->connect_errno){//检测连接
        die("连接失败:".$conn->connect_errno);
    }
    $sql="insert into stu (stu_num,stu_name) values ('6', '张三')";

    if ($conn->query($sql) === TRUE) {echo "=====新记录插入成功!=====";}
    else { echo "Error: " . $sql . "<br>" . $conn->error;}

    $conn->close();
    ?>

运行结果

D:\software\wampserver\bin\php\php7.3.5\php.exe D:\phpspace\test\connTest.php
=====新记录插入成功!=====
Process finished with exit code 0

虽然插入成功,但是出现乱码这很让人头疼。

解决

<?php
    $host="localhost";
    $user="root";
    $password="zzjava";
    $dbname="community";
    //创建连接
    $conn=new mysqli($host,$user,$password,$dbname);
    //设置编码格式为utf8
    $conn->query("SET NAMES utf8");
    if ($conn->connect_errno){//检测连接
        die("连接失败:".$conn->connect_errno);
    }
    $sql="insert into stu (id,name) values ('6', '赵六')";

    if ($conn->query($sql) === TRUE) {echo "=====新记录插入成功!=====";}
    else { echo "Error: " . $sql . "<br>" . $conn->error;}
    //关闭连接
    $conn->close();
    ?>

没错,就是加了一条$conn->query("SET NAMES utf8");(需要注意的是这里的utf8写成utf-8亲测是不行的)这样就解决了。

phpconn.jpg