Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/239.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何在MySQL表中模拟2个时间戳字段?_Php_Mysql - Fatal编程技术网

Php 如何在MySQL表中模拟2个时间戳字段?

Php 如何在MySQL表中模拟2个时间戳字段?,php,mysql,Php,Mysql,我知道mysql中每个表只能有1个时间戳。但是我需要两个。一个用于创建文章时,另一个用于每次更新。后者将在大部分时间发生变化,因此我决定将其作为时间戳字段。对于另一个问题,我如何用PHP准备时间,使其在插入数据库时看起来就像一个时间戳: 2011-07-29 03:28:20 如果这个字符串是用PHP编写的,通常的格式化方法是否有效,例如: $time = strtotime($timestamp); $date = date('n/d/Y @ g:i a', $time);

我知道mysql中每个表只能有1个时间戳。但是我需要两个。一个用于创建文章时,另一个用于每次更新。后者将在大部分时间发生变化,因此我决定将其作为时间戳字段。对于另一个问题,我如何用PHP准备时间,使其在插入数据库时看起来就像一个时间戳:

2011-07-29 03:28:20
如果这个字符串是用PHP编写的,通常的格式化方法是否有效,例如:

    $time = strtotime($timestamp);
    $date = date('n/d/Y @ g:i a', $time);

可以使用datetime字段来存储插入时间(使用mysql的now()函数)。 改为使用时间戳字段来存储更新时间

create table mytb (
id int not null auto_increment primary key,
article varchar(50),
ins_time datetime,
upd_time timestamp not null default current_timestamp on update current_timestamp
) engine = myisam;

insert into mytb (
article,ins_time) values ('bla bla bla', now());

update mytb set article = 'bla bla' where id = 1

您可以在
INSERT
UPDATE
查询中使用MySQL函数
NOW()

UPDATE table SET modified = NOW() WHERE id='$id'

您不需要让PHP参与其中。您可以在创建时间戳列上使用以下模式,默认为NULL,并在更新当前时间戳时使用

CREATE TABLE test.table (
  `row_inserted` TIMESTAMP NULL,
  `row_updated` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)

这是从

上的一个示例复制而来的。您有两个选项:使用
NOW()在SQL内部执行操作。

或者使用在PHP中创建的时间戳:

$now = time();
sprintf("UPDATE table SET modified =%d WHERE id=%d", $now, $id);
如果只有一次到数据库的往返,那么第一种方法非常理想:一次插入所有数据。 第二个选项允许您携带
$now
变量一段时间,然后重新使用它。例如,如果您在一个循环中插入多条记录:您肯定知道它们都具有相同的时间戳。后者的另一个优点是,数据库服务器和PHP之间的时间差无关紧要


注意:我使用sprintf是为了对SQL注入提供最低限度的安全性。然而,这并不是真正可靠的安全。您必须自己通过适当的数据库层来清理数据。

等等,谁说您只能有一个timestamp列?
$now = time();
sprintf("UPDATE table SET modified =%d WHERE id=%d", $now, $id);