PHP PDO: charset, set names?

前端 未结 9 720
孤独总比滥情好
孤独总比滥情好 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:20

    I test this code and

    $db=new PDO('mysql:host=localhost;dbname=cwDB','root','',
    array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
    $sql="select * from products  ";
    $stmt=$db->prepare($sql);
    $stmt->execute();
    while($result=$stmt->fetch(PDO::FETCH_ASSOC)){                  
        $id=$result['id'];
    }
    
    0 讨论(0)
  • 2020-11-22 07:23

    You'll have it in your connection string like:

    "mysql:host=$host;dbname=$db;charset=utf8"
    

    HOWEVER, prior to PHP 5.3.6, the charset option was ignored. If you're running an older version of PHP, you must do it like this:

    $dbh = new PDO("mysql:$connstr",  $user, $password);
    $dbh->exec("set names utf8");
    
    0 讨论(0)
  • 2020-11-22 07:25
    $conn = new PDO("mysql:host=$host;dbname=$db;charset=utf8", $user, $pass);
    
    0 讨论(0)
提交回复
热议问题