如何使用PDO设置time_zone

时间:2017-02-24 19:45:12

标签: php mysql pdo

我使用箭头SET NAMES UTF8

的PDO连接
$options = [ PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES UTF8" ];

但我会添加SET time_zone='America/Sao_Paulo'。但是在我试过的所有方法中,我得到了一个例外!

这是我的连接类:

//Conexãousandoobjeto PDO Singleton Pattern

/** @var PDO */
private static $connect = null;

/**
 * Conecta com o banco de dados com o pattern singleton
 * Retorna um objeto PDO!
 */
private static function Conectar(){

    try {

        Setup::checkLocal();

        if(self::$connect == null) {
            $dsn = 'mysql:host='.Setup::$host.';dbname='.Setup::$base;
            $options = [ PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES UTF8; SET time_zone='America/Sao_Paulo'" ];
            self::$connect = new PDO($dsn, Setup::$user, Setup::$pass, $options);
        }

    } catch (PDOException $e) {
        echo 'PDOException: erro ao conectar ao banco de dados.';
        //PHPErro($e->getCode(), $e->getMessage(), $e->getFile(), $e->getLine());
        die;
    }

    self::$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    //self::$connect->setAttribute(PDO::ATTR_ORACLE_NULLS, PDO::NULL_EMPTY_STRING);

    return self::$connect;
}

/** Retorna um objeto PDO Singleton Pattern */
public static function getConn(){
    return self::Conectar();
}

public static function prepareQuery($query, $params){

    $preparedQuery = self::getConn()->prepare($query);
    foreach ($params as $key => $value) {
        $preparedQuery->bindValue($key, $value);
    }

    $preparedQuery->execute();
    $result = $preparedQuery->fetchAll(PDO::FETCH_OBJ);

    self::$connect = null;

    return $result;
}

1 个答案:

答案 0 :(得分:-2)

这可能会对你有所帮助。试试吧!

$pdo = new PDO('mysql:host=localhost;dbname=exampletable', 
'exampleuser', 
'examplepassw', 
[PDO::MYSQL_ATTR_INIT_COMMAND =>"SET NAMES utf8;SET time_zone = 'Europe/London'"]);