문제

When trying to create a record in a table using phpActiveRecord I get the following error:

Invalid datetime format: 1292 Incorrect datetime value: '2013-06-20 11:59:08 PDT' for column 'created_at'

The code that is running:

$new_cart = new QuoteRequest();
$new_cart->status = "cart";
$new_cart->save();

I've tracked this down to the pertinent lines in phpActiveRecord. The file Connection.php, lines 55-59:

/**
 * Database's datetime format
 * @var string
 */
static $datetime_format = 'Y-m-d H:i:s T';

And the line that uses this (Connection.php, lines 457-466):

/**
 * Return a date time formatted into the database's datetime format.
 *
 * @param DateTime $datetime The DateTime object
 * @return string
 */
public function datetime_to_string($datetime)
{
  return $datetime->format(static::$datetime_format);
}

And where the value is converted (Table.php lines 394-412):

private function &process_data($hash)
{
    if (!$hash)
        return $hash;

    foreach ($hash as $name => &$value)
    {
        if ($value instanceof \DateTime)
        {
            if (isset($this->columns[$name]) && $this->columns[$name]->type == Column::DATE)
                $hash[$name] = $this->conn->date_to_string($value);
            else
                $hash[$name] = $this->conn->datetime_to_string($value);
        }
        else
            $hash[$name] = $value;
    }
    return $hash;
}

I am using MySQL version 5.6.10 and the created_at field is a timestamp.

Question: Is there something wrong with phpActiveRecord here, or is it a MySQL problem?

도움이 되었습니까?

해결책

static $datetime_format = 'Y-m-d H:i:s T';

I think you should remove that 'T' (which gives you PDT, i.e. the timezone abbreviation) as it is not part of the timestamp format.

Should be thus:

static $datetime_format = 'Y-m-d H:i:s';

다른 팁

The accepted answer works; however you're writing over the package's code. That means that whenever you update PHP-AR on your project you'll lose that change.

A better approach would be to override it on execution time when setting up AR on your project:

ActiveRecord\Config::initialize(function($cfg) {
  // [...] Your init config goes here
  ActiveRecord\Connection::$datetime_format = 'Y-m-d H:i:s';
});

Your init config may differ a little, so be sure to adapt it to your need.

Having the override on your project instead of changing the vendor's core files:

  1. Is good practice;
  2. Makes your customization clear for anyone that works on your project;
  3. Prevent code breaks if you ever update PHP-AR on your project.

The root cause of the issue is that you don't have a default timezone set.

You might see this on local and not the server because the server has the timezone set in the configuration. You can either set this locally in your php configuration or at the top of your source above the requiring of ActiveRecord.php using something like:

date_default_timezone_set('America/New_York');
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top