Skip to content
Advertisement

How to set pdo timezone at connection

I have this code where I connect to database and the code is working properly. However the now() function of MySQL is out of sync with PHP set default time zone function. I am comparing the PHP date with MySQL now. Therefore, I wanted to set the database time zone as well.

I wanted to set the database time upon connection. I have this code from this site I wanted to adapt it to mine. This is the code below. I came across this code and I thought it could be of help but I am finding it hard to implement with my already working code.

I got several error when I implemented it. One of which is.

Parse error: syntax error, unexpected ‘new’ (T_STRING), expecting function (T_FUNCTION) in /home/…/…classes/dbh.class.php on line 12. I thought may be I needed to put private and it still throw errors.

Please, how do I implement the two codes together

Link to the code I am adapting is this. Set timezone in PHP and MySQL

FULL CODE 1.(index.php)

2.(dbh.class.php)

This is where I am using the class 3. (user.class.php)

Advertisement

Answer

You can execute SET time_zone as an initial command. Although you really should use prepared statements all the time, this might be an acceptable hack.

However, I need to point out that such class is completely useless. PDO is a class already and wrapping the connection logic like that serves no purpose. What I would do instead is execute it procedurally without any class.

Now you can pass $pdo around to whichever class that needs the connection.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement