如何使用所需的时区将datetime插入数据库?

时间:2016-08-02 08:14:44

标签: php mysql datetime pdo

我想尝试插入按钮点击时自动设置的日期时间。我不介意任何按钮。我只是想知道格式是怎样的。我看到了这个语法date_default_timezone_set('Asia/Kuala_Lumpur');然而我正在使用PDO php并想要使用正确的时区将其插入数据库,并能够以更正确的格式再次调用时间。我是这种语法的新手。到目前为止,我只是把它放在我的查询之前,我试图回应它。它确实发生了变化,但是在插入时,它根本没有变化。当然是在我发布此代码之前。请帮忙。我应该把它放在哪里?

//=====================
date_default_timezone_set('Asia/Kuala_Lumpur');
echo date('Y-m-d H:i:s T', time());             

$query = " INSERT INTO record ( 
                bdatetime,
                bstatus,
                bmatricno_fk,
                serialno_fk
           ) VALUES (
                NOW(),
                'NEW',
                :bmatricno,
                :ses
           )"; 

foreach($ses as $s) {                   
    $query_params = array( 
        ':bmatricno' => $_POST['bmatricno'], 
        ':ses' => $s
    );

    try { 
        // Execute the query to create the user 
        $stmt = $db->prepare($query); 
        $result = $stmt->execute($query_params); 
    } catch(PDOException $ex) { 
        // Note: On a production website, you should not output $ex->getMessage(). 
        // It may provide an attacker with helpful information about your code.  
        die("Failed to run query: " . $ex->getMessage()); 
    }

1 个答案:

答案 0 :(得分:1)

date_default_timezone_set('Asia/Kuala_Lumpur');
$newDate = date('Y-m-d H:i:s T', time());


$query = " 
        INSERT INTO record ( 
            bdatetime,
            bstatus,
            bmatricno_fk,
            serialno_fk
        ) VALUES (
            :newDate,
            'NEW',
            :bmatricno,
            :ses
        )
    ";

foreach ($ses as $s) {

    $query_params = array(
        ':bmatricno' => $_POST['bmatricno'],
        ':ses' => $s,
        ':newDate' => $newDate
    );

    try
    {
        // Execute the query to create the user 
        $stmt = $db->prepare($query);
        $result = $stmt->execute($query_params);
    } catch (PDOException $ex)
    {
        // Note: On a production website, you should not output $ex->getMessage(). 
        // It may provide an attacker with helpful information about your code.  
        die("Failed to run query: " . $ex->getMessage());
    }
}

你可以试试这个。您可能应该阅读更多关于PDO的内容。

http://php.net/manual/en/book.pdo.php

在你的情况下

http://php.net/manual/en/pdostatement.bindparam.php