utf-8 data retrieve from database

2019-07-11 06:15发布

问题:

I have utf-8-general-ci in database..and inserted data in hebrew langugae.. now when i retrieve data it displays me string like ??????.. database connection is like this..

 function __construct($strHost='', $strDB='', $strUser='', $strPass='')
    {
        try{

            if($strHost != ''){$this->strHost = $strHost;}
            if($strDB != ''){$this->strDB = $strDB;}
            if($strUser != ''){$this->strUser = $strUser;}
            if($strPass != ''){$this->strPass = $strPass;}

  $this->objDB = new PDO("mysql:host=".$this->strHost.";port=3306;dbname=".$this->strDB,$this->strUser, $this->strPass, array( PDO::ATTR_PERSISTENT => true));
            if($this->objDB)
            {
                return $this->objDB;
            }
            else
            {
                echo "Database Connection Failed.";die;
            }
        }
        catch(Exception $objException)
        {
            echo $objException->getMessage();exit;
        }
    }

can anyone help please ?

回答1:

Add utf8 in your PDO connection as

 $this->objDB = new PDO("mysql:host=".$this->strHost.";port=3306;dbname=".$this->strDB, $this->strUser, $this->strPass,
 array( PDO::ATTR_PERSISTENT => true,
    PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));

Read http://php.net/manual/en/pdo.construct.php



标签: php utf-8