php - 如何更改 NOW() 时区

标签 php mysql timezone prepared-statement

我在 sql 查询中使用 NOW()。我想将其更改为另一个时区。这可能吗?

试过这个功能

class common {

    public function getTime() {
        $date = new DateTime();
        $date->setTimezone(new DateTimeZone('Europe/Paris'));
        return $date->format('Y-m-d H:i:s');
    }

}

出现以下错误

Catchable fatal error:  Object of class common could not be converted to string in line below

        $stmt = $this->db->prepare("INSERT INTO `items` 
      (`refno`, `color`, `size`, `qt`, `stackno`, `notes`, `price`, `add_date`)
      VALUES (?, ?, ?, ?, ?, ?, ?, $this->common->getTime())") or die($db->error);

我做错了什么?

最佳答案

该错误实际上是PHP错误,而不是SQL错误。尝试在字符串插值中评估复杂的变量扩展表达式并不像您那样工作。

尝试将对象放在 {} 大括号内:

$stmt = $this->db->prepare("INSERT INTO `items` 
      (`refno`, `color`, `size`, `qt`, `stackno`, `notes`, `price`, `add_date`)
      VALUES (?, ?, ?, ?, ?, ?, ?, {$this->common->getTime()})") or die($db->error);

参见手册页中的副标题复杂( curl )语法 http://php.net/manual/en/language.types.string.php


回复你的评论:

now getting this error on the same line: Trying to get property of non-object

您还没有说明如何设置 $this->common。根据您所展示的语法,common 需要是您的类 common 的对象实例。我猜你想在不实例化类的情况下调用 getTime() 函数。如果你想使用一个类的静态方法,你必须这样做:

class common {

    public static function getTime() {
        $date = new DateTime();
        $date->setTimezone(new DateTimeZone('Europe/Paris'));
        return $date->format('Y-m-d H:i:s');
    }

}

$stmt = $this->db->prepare("INSERT INTO `items` 
      (`refno`, `color`, `size`, `qt`, `stackno`, `notes`, `price`, `add_date`)
      VALUES (?, ?, ?, ?, ?, ?, ?, " . common::getTime() . ")") or die($db->error);

如果您不熟悉类和对象之间的区别以及 static 的用法,那么您需要做一些阅读,例如Object-Oriented PHP .

关于php - 如何更改 NOW() 时区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9165931/

相关文章:

php - 如何使用带有数据库中的值的复选框,其中数据库中的类型列(设置)codeigniter

php - 具有 1 对 1 关系的 SQL 删除

timezone - 将 IANA/Olson 时区数据库映射到缩写(如 EST、PST 等)

PHP 允许的内存大小

php - 将多语言js文件包含到PHP文件中

php - 如何从第一个查询中获取字段的值并在第二个查询中使用它

javascript - 如何在 JavaScript 中获取 UTC 时间戳?

javascript - 选定日期的开始日期和结束日期

php - 安装 opencart-1.5.5.1 时出错

php - 连接 PHP 数组中的元素