How to make PDO run SET NAMES utf8 each time I connect, In ZendFramework

后端 未结 8 864
迷失自我
迷失自我 2020-11-28 04:11

How to make PDO adapter run SET NAMES utf8 each time I connect, In ZendFramework. I am using an INI file to save the adapter config data. what entries should I add there?

8条回答
  •  心在旅途
    2020-11-28 04:36

    You just have to execute this command before you start queries, you only have to execute it once before the queries and not for every query.

    $pdo->query("SET NAMES 'utf8'");
    

    Full example

    $servername = "localhost";
    $username = "root";
    $password = "test";
    $dbname = "yourDB";
    
    try {
        $pdo = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    
        $pdo->query("SET NAMES 'utf8'");
    
        //set the PDO error mode to exception
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
        $sql = "SELECT name FROM nations";
        foreach ($pdo->query($sql) as $row) {
           echo "";
        }
    
    
    } catch(PDOException $e) {
        echo "Error: " . $e->getMessage();
    }
    $pdo = null; 
    

提交回复
热议问题