1

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?

Ralph Willgoss
  • 11,750
  • 4
  • 64
  • 67
BigOrinj
  • 243
  • 2
  • 6
  • 14
  • [**Please, don't use `mysql_*` functions in new code**](http://bit.ly/phpmsql). They are no longer maintained and the [deprecation process](http://j.mp/Rj2iVR) has begun on it. See the [**red box**](http://j.mp/Te9zIL)? Learn about [*prepared statements*](http://j.mp/T9hLWi) instead, and use [PDO](http://php.net/pdo) or [MySQLi](http://php.net/mysqli) - [this article](http://j.mp/QEx8IB) will help you decide which. If you choose PDO, [here is a good tutorial](http://j.mp/PoWehJ). – tereško Nov 03 '12 at 13:51

3 Answers3

1
mysql_query("INSERT INTO Blog (Date, Title, Message, Image) 
            VALUES(now(), '" . $_POST[Title] . "' , '" . $_POST[Message] . "' , 
            '" . $_POST[Image] . "' ) ") or die(mysql_error());
Vikram Jain
  • 5,498
  • 1
  • 19
  • 31
1

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 :)

CodeAngry
  • 12,760
  • 3
  • 50
  • 57
0

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

Morgan Wilde
  • 16,795
  • 10
  • 53
  • 99