Reputation: 11
I have this page below, which is the action when you submit a form. I am wondering how you can add a time function to this, to add the time that the form was submitted to my database table in the row "time". I have tried numerous things and can't get them to work :/
<?php
require 'db/connect.php';
if(isset($_POST['submitted']))
{
$player = $_POST['inputWho'];
$offense = $_POST['inputWhat'];
$where = $_POST['inputPlace'];
$proof = $_POST['inputProof'];
$comments = $_POST['inputComments'];
$sqlinsert = "INSERT INTO offenses (player, reason, place, proof, comments) VALUES ('$player', '$offense', '$where', '$proof', '$comments')";
if (!mysqli_query($db, $sqlinsert)) {
die('Error inserting new record.'. "<br />". mysqli_error($db));
} //end of nested if
} //end of if
header("Location: success.php");
?>
Upvotes: 0
Views: 454
Reputation: 5932
The way I usually approach this problem is to add a column to the table that looks like this:
created_time datetime default current_timestamp
You don't even have to include it in your INSERT statement, it will get set automatically when you create the row.
EDIT: The above statement only works with type TIMESTAMP, not DATETIME. (Many people are probably still on MySQL 5.5 or earlier at present.) This is discussed in the manual here: http://dev.mysql.com/doc/refman/5.6/en/timestamp-initialization.html
You can avoid this version problem by using Skywalker's answer. (Or by not using MySQL.)
If you also need the column set when you update, that's a different issue.
I find it's generally preferable to get the time from inside the database rather than supplying one from the web server. This avoids any problems with your web server time getting slightly out of sync with your database server. (You may even have multiple web servers that are out of sync with each other.)
Upvotes: 4
Reputation: 2441
Try this:
date_default_timezone_set('America/Los_Angeles');
$dateEnquiry = date("Y-m-d H:i:s", time());
$sqlinsert = "INSERT INTO offenses (player, reason, place, proof, comments, time) VALUES ('$player', '$offense', '$where', '$proof', '$comments', '$dateEnquiry')";
Upvotes: 0
Reputation: 826
Make your sql like this:
$sqlinsert = "INSERT INTO offenses (player, reason, place, proof, comments, time) VALUES ('$player', '$offense', '$where', '$proof', '$comments', NOW())";
Make use of MySQL function NOW().
Upvotes: 1