php - 如何从 MySQL 数据库获取时间戳?

标签 php mysql

如果我调用函数 getDate_created();,我的查询将不会显示时间戳。我怎样才能解决这个问题?函数 getAll() 确实有效。

<?php

class Post
{
    public $date_created;


    public function getDate_created()
    {
        return $this->date_created;
    }

    public function setDate_created($date_created)
    {
        $this->date_created = $date_created;

        return $this;
    }

    public static function getAll()
    {
        $conn = Db::getInstance();
        $result = $conn->query('SELECT * FROM images');

        return $result->fetchAll(PDO::FETCH_CLASS, __CLASS__);
     }
 }


$posts = Post::getAll();

$timepost = new Post();
$t = $timepost->getDate_created();
var_dump($t);

表格图像:

CREATE TABLE `images` (
   `id` int(11) NOT NULL,
   `user_id` int(11) NOT NULL,
   `img_description` varchar(255) NOT NULL,
   `date_created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
   `file_path` varchar(255) NOT NULL
   ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Var_dump($t) 显示结果为 NULL。

最佳答案

当您执行 $timepost = new Post();

时,您正在创建 Post 的新实例

如果您想从数据库中读取其中一篇帖子,您应该从来自 getAll() 方法的帖子中读取一篇(或多篇)。

例如:

$posts = Post::getAll();

foreach($posts as $post) {
    var_dump($post->getDate_created());
}

//or

var_dump($posts[0]->getDate_created());

关于php - 如何从 MySQL 数据库获取时间戳?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55969859/

相关文章:

mysql - 从第 5 个值开始添加

php - 从涉及多个表的查询中获取 CSV

php - 我将如何去显示我的数据库中的用户个人资料图片?

javascript - 获取用 PHP 和 javascript 完成游戏的成本时间

javascript - 如何在javascript中运行php数组的循环(google graph api)

php - 我的网站容易受到 sql 注入(inject)的攻击吗? (PHP 新手)

php - 如何在php中提交表单时使用isset输入为数组分配多个值

php - 通过用户 ID 在 WooCommerce 中获取单个客户的所有订单和订单数据

MySQL:计算值/频率对的标准偏差

mysql - 如何在 sequelize 中关联和填充模型?