php mysql connection string characterEncoding=UTF8

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
markthien
Forum Commoner
Posts: 33
Joined: Fri Feb 13, 2009 7:50 pm

php mysql connection string characterEncoding=UTF8

Post by markthien »

Hi guys,

In java, when connecting to mysql db, I need to set like useUnicode=true&characterEncoding=UTF8 in the connection string:

Code: Select all

     Class.forName("com.mysql.jdbc.Driver").newInstance();
      con = DriverManager.getConnection("jdbc:mysql://mydb.com/mydb?user=mydb&password=mydb&useUnicode=true&characterEncoding=UTF8");
I just need to know how can I concate the "useUnicode=true&characterEncoding=UTF8" in php mysql connection string, which typically look like :

Code: Select all

class DBConnection {
    
    private $con = null;
    private $connection_string = 'mysql:host=localhost;dbname=mydb';
    private $username = 'mydb';
    private $password = 'mydb';
    
    function __construct() {
        try {
            $this->con = new PDO($this->connection_string, $this->username, $this->password);
            $this->con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch(PDOException $e) {
            error_log($e->getMessage());
        }
    }
    
    public function getConnection(){
        return $this->con;
    }
    
    function closeConnection(){
        $this->con = null;
    }
}
Appreciate any advice pls. Thanks !

regards,
Mark
dejvos
Forum Contributor
Posts: 122
Joined: Tue Mar 10, 2009 8:40 am

Re: php mysql connection string characterEncoding=UTF8

Post by dejvos »

If you mean output encoding you have to use SQL command

Code: Select all

SET NAMES utf8;
in PHP code it seems like:

Code: Select all

mysql_query("SET NAMES utf8");
Post Reply