如何将日期时间插入到具有所需时区的数据库中


How to insert datetime into database with desired timezone?

我想尝试插入单击按钮时自动设置的日期时间。我不介意那个按钮。我只是想知道格式是什么样子的。我看到了这个语法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()); 
    }
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