简体   繁体   中英

Unable to Set MySQL Timezone using PDO in PHP

Duplicate marked link address the part "how to configure time zone?", I followed the same but it gives me an error as explained below

I am seeing following error on my php page

Cannot execute queries while other unbuffered queries are active.  Consider using PDOStatement::fetchAll().  Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute.

I have gone throught multiple questions of same nature, but unable to understand the problem in my specific case.

Here is the query I am trying to run

SELECT  count(*) as total FROM  my_company en
                ORDER BY  cmpid ASC

Note: This is the first query, no query before this one is executed. I though I might be missing $stmt->closeCursor(); but that is not the case.

However I do have made some change to set database time zone My code work fine for following code

$pdo = new PDO ( "mysql:host=$hostname;dbname=$dbname", $username, $password );

I wanted to achieve following thing (setting time zone of mysql)

mysql_query("SET time_zone = 'UTC';SET NAMES utf8 ;");

So for PDO I made following change and now my code does not work.

$pdo= new PDO ( "mysql:host=$hostname;dbname=$dbname", 
                                                $username, $password, 
                                                array(PDO::MYSQL_ATTR_INIT_COMMAND =>"SET NAMES utf8;SET time_zone = 'UTC'") );

Here is the code If that might help

try {

    $statement = $pdo->prepare ( $sql );
    $statement->execute(); //exception on this line
    $result =  $statement->fetch ( PDO::FETCH_ASSOC );
    $statement->closeCursor();
    unset($statement);
} catch ( PDOException $e ) {
    sqlDie("Error: ", $e->getMessage(), $e->getCode(), array('exception' => $e));
}

My System Configurations

Windows 7
PHP 5.4.12
MySQL 5.6.12
Apache 2.4.4

This is a dynamic way to set MySQL timezone depends on PHP timezone

date_default_timezone_set('UTC');
$time_offset = date('P',time()); // +00:00
$pdo->query("SET time_zone='$time_offset';");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM