我需要我的系统来获取系统当前时间

时间:2013-12-17 13:04:35

标签: php mysql

我的系统是用PHP和MySQL开发的,有两个名为Time_inTime_out的HTML字段。

我希望这两个字段都能获取系统当前时间。

您建议使用什么代码?

下面是一行代码,用于插入一些字段和Time_in , Time_out字段。

$sql = "INSERT INTO $tbl_name VALUES ('$BID', '$Route', '$Driver_Name',
                 '$Driver_phone_no', '$Time_in', '$Time_out', '$Date' , '$Comment')";

2 个答案:

答案 0 :(得分:5)

使用NOW()获取当前日期和时间。

答案 1 :(得分:2)

您可以使用NOW()设置当前时间戳,或设置insert trigger(也可能更新触发器),这样您就不需要记住为这些设置显式设置值两个领域。

但要小心,如果您需要在设置了此类触发器的表中“按摩”数据,并且您不希望所有行都更新为新的time_in / time_out值。

以下是创建表和触发器的示例。然后将一行插入该表中,之后不久更新。请注意,即使UPDATE仅显式更新注释,time_out值也会更改。

mysql> create table tableName (`id` int(10) unsigned not null auto_increment, `route` varchar(50), `driver_name` varchar(50), `comment` blob default '', `time_in` timestamp , `time_out` timestamp , primary key(`id`)) engine=MyISAM DEFAULT CHARSET=utf8;
Query OK, 0 rows affected, 1 warning (0.07 sec)

mysql> create trigger tableName_bInsert BEFORE INSERT on tableName for each row set new.time_in=NOW();
Query OK, 0 rows affected (0.11 sec)

mysql> create trigger tableName_bUpdate BEFORE UPDATE on tableName for each row set new.time_out=NOW();
Query OK, 0 rows affected (0.09 sec)

mysql> insert into tableName set route="Belfast-Tralee", driver_name="Ken", comment="Pick up dogs. In.";
Query OK, 1 row affected (0.00 sec)

mysql> select * from tableName;
+----+----------------+-------------+-------------------+---------------------+---------------------+
| id | route          | driver_name | comment           | time_in             | time_out            |
+----+----------------+-------------+-------------------+---------------------+---------------------+
|  1 | Belfast-Tralee | Ken         | Pick up dogs. In. | 2013-12-17 13:51:13 | 0000-00-00 00:00:00 |
+----+----------------+-------------+-------------------+---------------------+---------------------+
1 row in set (0.00 sec)

mysql> update tableName set comment="Dogs - out" where id = 1;
Query OK, 1 row affected (0.02 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> select * from tableName;
+----+----------------+-------------+------------+---------------------+---------------------+
| id | route          | driver_name | comment    | time_in             | time_out            |
+----+----------------+-------------+------------+---------------------+---------------------+
|  1 | Belfast-Tralee | Ken         | Dogs - out | 2013-12-17 13:51:37 | 2013-12-17 13:51:37 |
+----+----------------+-------------+------------+---------------------+---------------------+
1 row in set (0.00 sec)

mysql>