ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

php-如何更改NOW()时区

2019-12-01 20:25:47  阅读:310  来源: 互联网

标签:timezone prepared-statement mysql php


我在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);

请参见手册第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.

标签:timezone,prepared-statement,mysql,php
来源: https://codeday.me/bug/20191201/2083299.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有