Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
203 views
in Technique[技术] by (71.8m points)

php - How can I make a column that stores the time that row was created in mysql?

After tons of googling I could not find an answer. I want to create a column in mysql that stores the the time that row was created as HH:MM:SS

I'm making a chat room and the table currently has a column for the message and id

I dont want do use timestamp or datetime as I don't want to have date month year etc. just Hour min and sec.

I tried time but it always say the time is 00:00:00

EDIT: I guess I want to be able to echo only time from time stamp.

I tried echo '<div><p>User@' . substr($value['Time'], 11) . '->' . $value['message'] . '</p></div>'; But it does not work.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Edited Answer

If you want to use a regular TIMESTAMP field in MySQL, first create the field.

ALTER TABLE  `YourTable` ADD  `LastAccessed` TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ;

Once you have setup the field you can leave it alone. When you insert a record pass null as the value and it will default to the current time. When you update the record the time will be adjusted.

To obtain the time from the TIMESTAMP field you will need to run your select query and get your results. For illustrative purposes, this would look something like the following:

//Integrate this into your existing code
$result = mysqli_query($connection, "SELECT LastAccessed FROM YourTable"); //get only the time field for this example
$row = mysqli_fetch_array($result);
$time = new DateTime($row['LastAccessed']); //The constructor accepts the time information as an argument
echo $time->format("H:i:s"); //This is your time information.

Since you have a TIMESTAMP field now, not only will the database take responsibility for updating it with the correct time, but you can always modify the $time->format() method's argument to produce a string with time data in a variety of different ways.

The timestamp gets abstracted and your application gain flexibility.

Win-Win, right?

Original Answer

Create a char(8) column in MySQL and then send it the output from a call to:

date("H:i:s");

Although using a timestamp field in MySQL would be optimal, considering you can have it update when the record is interacted with. You don't have to use the entire timestamp.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...