我在 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/