Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MYSQL set timezone in PHP code

How can I change MYSQL TIMEZONE to GMT format like this function in PHP: /SET GMT TIMEZONE/ date_default_timezone_set('Etc/GMT');

My DB class is here:

class DB {
    private static $instance;
    private $MySQLi;

    private function __construct(array $dbOptions){

        $this->MySQLi = @ new mysqli(   $dbOptions['db_host'],
                                        $dbOptions['db_user'],
                                        $dbOptions['db_pass'],
                                        $dbOptions['db_name'] );

        if (mysqli_connect_errno()) {
            throw new Exception('Database error.');
        }

        $this->MySQLi->set_charset("utf8");
    }

    public static function init(array $dbOptions){
        if(self::$instance instanceof self){
            return false;
        }

        self::$instance = new self($dbOptions);
    }

    public static function getMySQLiObject(){
        return self::$instance->MySQLi;
    }

    public static function query($q){
        return self::$instance->MySQLi->query($q);
    }

    public static function prepare($q){
        return self::$instance->MySQLi->prepare($q);
    }

    public static function esc($str){
        return self::$instance->MySQLi->real_escape_string(htmlspecialchars($str));
    }

}

And my queries like this in other files:

DB::query('UPDATE `calendar_data` SET `data` = "'.DB::esc(json_encode($array)).'", `upcoming_time` = "'.date('Y-m-d H:i:s', $upcoming).'", `time_now` = NOW() WHERE `id` = "1"');

Where should I insert my query to the class for run it once?

Thanks!

$this->MySQLi->set_charset("utf8");
$this->MySQLi->query("SET timezone = 'GMT'");
  • Doesn't work. If I use NOW(), server time was inserted (GMT-4). Where is a problem???
like image 614
XTRUST.ORG Avatar asked Sep 06 '12 09:09

XTRUST.ORG


People also ask

What timezone is UTC for PHP?

The default timezone for PHP is UTC regardless of your server's timezone. This is the timezone used by all PHP date/time functions in your scripts. See PHP's list of supported timezones to find the names of all possible timezones you can use for the date.

How do I set timezone in MySQL 8?

Simply run this on your MySQL server: SET GLOBAL time_zone = '+8:00'; Where +8:00 will be your time zone.


1 Answers

Try the following:

$this->MySQLi->query("SET time_zone = '+0:00'");

Using named timezones will only work if the time zone information tables in the MySQL database have been created and populated.

like image 117
Mike Avatar answered Oct 19 '22 20:10

Mike