MySQL TIMESTAMP 字段
mysql 建立字段的时候 time 选择 TIMESTAMP 后 ,PHP 如果传递正确的时间数据呢?
mysql 的 TIMESTAMP 到底是什么性质的呢?
要搞清楚
使用 PHP 从数据库中取出的时间的数据类型
使用 PHP 向数据库中插入的时间的数据类型
测试环境:
Windows 2016 LTS
Apache 2.4.23
OpenSSL 1.0.2j
Mod_fcgid 2.3.9
PHP 7.0.12
MySQL 5.5.53
CodeIgniter 3.1.10
配置CI中的数据库application/config/database.php
创建Model(模型)
连接数据库
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Time_test extends CI_Model {
public function __construct()
{
$this->load->database();
}
}
确定PHP时间函数的数据类型
public function times()
{
$t = time();
var_dump($t);die;
}
int(1554692204)
INSERT INTO time_test (time) VALUES ('1554692204');
INSERT INTO time_test (time) VALUES ('2019-04-08 11:16:23');
SELECT * FROM time_test;
+----+---------------------+
| id | time |
+----+---------------------+
| 1 | 0000-00-00 00:00:00 |
| 2 | 2019-04-08 11:16:23 |
+----+---------------------+
2 rows in set (0.00 sec)
MySQL 的 timestamp 接受 2019-04-08 11:16:23 这种格式的时间输入
从数据库中取出时间数据,并查看数据类型
模型(数据库)
public function time_view()
{
$query = $this->db->get('time_test')->result();
return $query;
}
控制器
public function times()
{
$result['results'] = $this->time_test->time_view();
var_dump($result);
}
结果
array(1) {
["results"]=>
array(2) {
[0]=>
object(stdClass)#20 (2) {
["id"]=>
string(1) "5"
["time"]=>
string(19) "0000-00-00 00:00:00"
}
[1]=>
object(stdClass)#21 (2) {
["id"]=>
string(1) "6"
["time"]=>
string(19) "2019-04-08 11:16:23"
}
}
}
总结
MySQL TIMESTAMP 类型的时间在PHP中是以string的形式返回的
输入输出都是2019-04-08 11:16:23这种格式
PHP中的time()函数则是int类型的数据 int(1554692204)
剩下的就是两者之间的转换了
PHP time() ---> MySQL timestamp
数据库(模型)
public function time_insert($data)
{
$this->db->insert('time_test', $data);
}
控制器
public function insert_time()
{
$t = time();
$tt = date("Y-m-d H:i:s",$t);
$data = array(
'time' => $tt
);
$this->time_test->time_insert($data);
}
结果
SELECT * FROM time_test;
+----+---------------------+
| id | time |
+----+---------------------+
| 5 | 0000-00-00 00:00:00 |
| 6 | 2019-04-08 11:16:23 |
| 7 | 2019-04-08 21:32:17 |
+----+---------------------+
3 rows in set (0.00 sec)