我的系统使用PHP和MySQL开发,有两个名为Time_in
和Time_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')";
使用NOW()获取当前日期和时间。
您可以使用NOW()来设置当前时间戳,或者设置插入触发器(可能还有更新触发器),这样您就不需要记住显式设置这两个字段的值。
但是,如果您需要在设置了此类触发器的表中"按摩"数据,并且不希望所有行都更新为新的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>