简体   繁体   中英

how can i get the timestamp from mySQL database?

my query won't show a timestamp if i call the function getDate_created();. how can i fix this? The function getAll() does work.

<?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);

the table images:

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) shows NULL as result.

You are creating a new instance of Post when you do $timepost = new Post();

If you want to read one of those posts from database you should read one (or more) from those that came from getAll() method.

Ex:

$posts = Post::getAll();

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

//or

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

There is no point of setting timestamp value to the attribute in this case because you are getting ALL records so it will get value of the last one (it will override every previous one). It will make sense to set value to $this->date_created attribute only when you are fetching ONE record from DB, if you want to do it that way. In general you just need to make sth like:

$received_data = $result->fetch(PDO::FETCH_ASSOC);
$this->date_created = $received_data['date_created'];

This solution will work ONLY FOR SINGLE record in assoc array. If you really want to make it for all records, just use simple foreach() loop iterating over received data from query.

If you need all of records from DB, you do not want to (trust me) set it to attribute (unless you want to have array of objects but you would need to rebuild quite a lot of your current code and it is not efficient).

In your case I would recommend to just use returned array without setting values to attributes.

Also, I don't recommend using getters and setters in this case, you can achieve the same effect by simply using $timepost->created_date (of course you need to set value to that attribute before).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM