PHP PDO: charset, set names?

前端 未结 9 887
孤独总比滥情好
孤独总比滥情好 2020-11-22 06:49

I had this previously in my normal mysql_* connection:

mysql_set_charset(\"utf8\",$link);
mysql_query(\"SET NAMES \'UTF8\'\");

Do I need it

9条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 07:15

    This is probably the most elegant way to do it.
    Right in the PDO constructor call, but avoiding the buggy charset option (as mentioned above):

    $connect = new PDO(
      "mysql:host=$host;dbname=$db", 
      $user, 
      $pass, 
      array(
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"
      )
    );
    

    Works great for me.

提交回复
热议问题