mysql_query("INSERT INTO Blog (Date, Title, Message, Image)
VALUES(now(), '" . $_POST[Title] . "' , '" . $_POST[Message] . "' ,
'" . $_POST[Image] . "' ) ") or die(mysql_error());
Get Server time and insert into Mysql table via a Form
-
30-07-2021 - |
Question
I have a form that posts the Date, Title, Message and Image into an SQL table. It all works fine, except the form, it has a field that I have to manually enter the date and time.
What I want to know is how can I get the PHP to get the date & time (GMT time) of when the form button is pressed and post it into the "time" section of my sql table instead of me doing it manually, I'm using this as a ultra lightweight CMS blog.
This is my insert.php
mysql_query("INSERT INTO Blog
(Date, Title, Message, Image)
VALUES('$_POST[Date]', '$_POST[Title]' , '$_POST[Message]' , '$_POST[Image]' ) ")
or die(mysql_error());
echo "1 record added";
This is my form
<form action="insert.php" method="post">
<span class="label">Date: </span> <input type="text" class="dateField" name="Date" />
<span class="label">Title: </span> <input type="text" class="titleField" name="Title" />
<span class="label">Message: </span> <textarea name="Message" class="messageField" maxlength="1000" cols="0" rows="0"></textarea>
<span class="label">Image URL: </span> <input type="text" class="ImageField" name="Image" />
<input type="submit" class="submitBtn"/>
</form>
I want the server to add the Time/Date instead of me typing it in manually. Is this easily done?
Solution
OTHER TIPS
MySQL's NOW()
(local time or server time) or UTC_TIMESTAMP()
(GMT or UTC) will do the trick.
Replace '$_POST[Date]'
with NOW()
or UTC_TIMESTAMP()
and you're done :)
Use the PHP time()
function to get the time of your script activation.
An example would be mysql_query("INSERT INTO Blog SET date = '".time()."'")
More on it here http://php.net/manual/en/function.time.php
By the way, you should transition out of using the mysql extension into either mysqli or PDO MySQL, read about why here http://lt1.php.net/manual/en/intro.mysql.php