将utf8设置为与PDO的mysql连接

时间:2015-11-18 05:02:01

标签: php mysql pdo utf-8

我这里有一个大问题。我的mysql表的许多行都强调数据,当我使用javascript获取这些信息时,它返回FATAL ERROR 200.我想知道我是否可以获取UTF8中的所有数据并将其设置在MySQL Connection上。 这是我的连接文件

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
class dbconfig {
    protected static $host = "";
    protected static $username = "";
    protected static $password = "";
    protected static $dbname = "";
    static $con;

    function __construct() {
        self::$con = self::connect(); 
    }

    protected static function connect() {
        try {
            $link = mysqli_connect(self::$host, self::$username, self::$password, self::$dbname); 
            if(!$link) {
                throw new exception(mysqli_error($link));
            }
            return $link;
        } catch (Exception $e) {
            echo "Error: ".$e->getMessage();
        } 
    }

    public static function close() {
        mysqli_close(self::$con);
    }

    public static function run($query) {
        try {
            if(empty($query) && !isset($query)) {
                throw new exception("Query string is not set.");
            }
            $result = mysqli_query(self::$con, $query);
            self::close();
            return $result;
        } catch (Exception $e) {
            echo "Error: ".$e->getMessage();
        }
    } 
}

1 个答案:

答案 0 :(得分:0)

解决方案

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
class dbconfig {
    protected static $host = "";
    protected static $username = "";
    protected static $password = "";
    protected static $dbname = "";
    static $con;

    function __construct() {
        self::$con = self::connect(); 
    }

    protected static function connect() {
        try {
            $link = mysqli_connect(self::$host, self::$username, self::$password, self::$dbname); 
            mysqli_set_charset($link,"utf8");
            if(!$link) {
                throw new exception(mysqli_error($link));
            }
            return $link;
        } catch (Exception $e) {
            echo "Error: ".$e->getMessage();
        } 
    }

    public static function close() {
        mysqli_close(self::$con);
    }

    public static function run($query) {
        try {
            if(empty($query) && !isset($query)) {
                throw new exception("Query string is not set.");
            }
            $result = mysqli_query(self::$con, $query);
            self::close();
            return $result;
        } catch (Exception $e) {
            echo "Error: ".$e->getMessage();
        }
    } 
}
相关问题