I have a my sql data base in which i have a field to store date. What I want to do is to store the current date to that field when i insert a new record.
My php code in Codeigniter to insert a new entry
$commentData = array(
'comment'=>$message,
'docid'=>$_GET['id'],
'username'=>$owner,
'commenter'=>$currentUser,
//here i need to add my new date entry
);
$this->showSearchResult_model->addComment($commentData);
In my Model
$this->db->insert('comment', $comment);
How can I edit this to insert the current date
Native PHP:
'date_created' => Date("Y/m/d H:i:s"), //this is the default mysql formating for DATETIME
Or using codeigniter DB helpers, on your showSearchResult_model model in the addComment() method, right before you use the $this->db->insert
$this->db->set('date_creted','now()',false); //false is here to skip escaping
more info here: http://ellislab.com/codeigniter/user-guide/database/active_record.html
Definition and Usage:
NOW() returns the current date and time.
Syntax:
NOW()
Example:
The following SELECT statement:
SELECT NOW(), CURDATE(), CURTIME()
will result in something like this:
NOW() CURDATE() CURTIME()
2008-11-11 12:45:34 2008-11-11 12:45:34
Example:
The following SQL creates an "Orders" table with a datetime column (OrderDate):
CREATE TABLE Orders
(
OrderId int NOT NULL,
ProductName varchar(50) NOT NULL,
OrderDate datetime NOT NULL DEFAULT NOW(),
PRIMARY KEY (OrderId)
)
Notice that the OrderDate column specifies NOW() as the default value.
As a result, when you insert a row into the table, the current date and time are automatically inserted into the column.
Now we want to insert a record into the "Orders" table:
INSERT INTO Orders (ProductName) VALUES ('Jarlsberg Cheese')
The "Orders" table will now look something like this:
OrderId ProductName OrderDate
1 Jarlsberg Cheese 2008-11-11 13:23:44.657
Change datecolumn to be the name of the column where the date is stored:
$commentData = array(
'comment'=>$message,
'docid'=>$_GET['id'],
'username'=>$owner,
'commenter'=>$currentUser,
'datecolumn'=>date('Y-m-d')
);
That is assuming you are using the date data type for that field. If it is actually a timestamp you would do this instead:
$commentData = array(
'comment'=>$message,
'docid'=>$_GET['id'],
'username'=>$owner,
'commenter'=>$currentUser,
'datecolumn'=>time()
);
Hope this will help you
$commentData = array(
'comment'=>$message,
'docid'=>$_GET['id'],
'username'=>$owner,
'commenter'=>$currentUser,
'date' => date("Y-m-d",time())
);
$commentData = array(
'comment'=>$message,
'docid'=>$_GET['id'],
'username'=>$owner,
'commenter'=>$currentUser,
'date' => now()
);`
Related
I'm playing with wordpress $wpdb function.
First of all, I want to create a database table with a column corresponding to the time, so that I can save user actions into this table and know when they did it.
Creating a table:
$sql = "CREATE TABLE IF NOT EXISTS $table_name (
id INT NOT NULL AUTO_INCREMENT,
actiontime NOT NULL DATETIME,
PRIMARY KEY (id)
) $charset_collSate;";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
// execute the query
dbDelta( $sql );
Is this correct? Will it create a DATETIME field that I'm after? I would want a time stamp such that I can get the difference on minute/second intervals.
Inserting in such table:
$wpdb->insert($table_name, array(
'actiontime' => now()
));
Will this work?
I can't check it manually, because I'm developing on a side machine and only have ftp access to live-server and notepad. I can't test anything locally.
I use this php function to get the current value for a MySQL DATETIME field.
/**
* Return current date time.
*
* #return string ISO date time (Y-m-d H:i:s)
*/
function now()
{
return date('Y-m-d H:i:s');
}
There are a few options you could consider,
If you're using plain old PHP and MySQL, you can use the SQL now() function to insert data into a timestamp field like this,
INSERT INTO projects (actiontime) VALUES (now())
Another options would be to use a PHP variable such as, $timestamp = date('Y-m-d G:i:s'); and inserting it in a SQL query:
$timestamp = date('Y-m-d G:i:s');
INSERT INTO projects (actiontime) VALUES ($timestamp);
Hope it helps!
try PHP time() for epoch timestamp
I don't want to update my timestamp field when update. I need to keep previous datetime in that field. But its updating automatically even I tried following
$data = array(
'start_time' => $start,//previous datetime
'user_id' => $agent_id,
....
);
$this->db->where('id', $chat_id)->update('chat_state', $data );
When I leave $start or force with previous datetime. Not work in both cases. Its updating with CURRENT TIMESTAMP in both cases
whats wrong here??
Connect to your mysql server using MySQL Workbench, to check your table's schema, by running the following queries:
USE mydatabase;
SHOW CREATE TABLE mytable;
I bet you'll see something like ON UPDATE CURRENT_TIMESTAMP associated with your start_time field.
Note that, relying on DBMS to auto-update values is not a good practice; It gives you surprises, and you end up spending hours to figure out the issue.
Let's remove the "ON UPDATE CURRENT_TIMESTAMP" clause, like this:
ALTER TABLE mytable MODIFY start_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP;
This should solve the problem.
Read more about TIMESTAMP's behaviors in different situations.
Follow these steps
Select exist value (start_time)
Update exist value to new field
insert new value
01 Select current value in db
$query = $this->db->query("SELECT start_time FROM chat_state WHERE user_id = $chat_id");
$result = $query->result_array();
02 Update exist value
$data = array(
'old_time' => $result[0]['start_time'] // move start_time to new field
);
$this->db->where('id', $chat_id)->update('chat_state', $data );
03 insert new value
$data = array(
'start_time' => date('Y-m-d H:i:s'), // new Time stamp
'user_id' => $agent_id
);
$this->db->where('id', $chat_id)->update('chat_state', $data );
Probably you have the column type as DATETIME; you need to change the type to TIMESTAMP and default null. It will not be updated automatically.
Then, while inserting the data
'start_time'=>date("Y-m-d H:i:s")
And when you want to print it in view
date('d-M-y', strtotime($record['start_time']));
The table structure is like that
start_time TimeStamp null
end_time TimeStamp null
The problem is , I would like to get all record within the start time and endtime, and all the value that has null start time & end time value (that means the record is not restrict by time)
$this->db->where('start_date <=', now());
$this->db->where('end_date >', now());
tried some sql for the first requirement but no luck , thanks for helping
It sounds like the query logic you need would go something like this:
...
WHERE NOW() BETWEEN start_date AND end_date
OR (start_date IS NULL AND end_date IS NULL)
To do this with Codeigniter's Active Record, try:
$this->db->where('NOW() BETWEEN start_date AND end_date');
$this->db->or_where('start_date IS NULL AND end_date IS NULL');
Alternatively, you could put the whole thing into one statement:
$where = 'NOW() BETWEEN start_date AND end_date OR (start_date IS NULL AND end_date IS NULL)';
$this->db->where($where);
You would probably need to have a compound query.
$within_range = array('start_date <=' => now(), 'end_date =>' => now());
$not_restricted = array('start_date IS NULL' => null, 'end_date IS NOT NULL' => null)
$this->db->where($within_range)->or_where($not_restricted);
see more about the associative array and or_where syntax at https://ellislab.com/codeigniter/user-guide/database/active_record.html#select
of course you can query using raw sql:
$this->db->select('select ...');
I'm writing a PHP/MySQL program. I need to add the current date each time a new record to the TABLE is added. I have a field called DATE_ADDED. I'm confused how to use CURDATE() function from MySQL to write this to the TABLE. Or should I from PHP use a date function to get today's date and pass it as a variable to be written to the TABLE? I don't need a TIMESTAMP, just YYYY-MM-DD.
Thanks!
You have to try with php like
$today = date("Y-m-d");
and then while adding data to your db give this value with the remaining
INSERT INTO table_name ( field1, field2,...DATE_ADDED )
VALUES
( value1, value2,...CURDATE());
You can set it as the default value for that column date_added in the table definition like so:
date_added TIMESTAMP DEFAULT CURRENT_TIMESTAMP
$regdate=date('Y-m-d');
$sql = "INSERT INTO table_name (fld_name1, fld_name2,fld_regdate) VALUES ('value1', 'value2', '$regdate')";
$rs = mysql_query($sql) or die('ERROR:' mysql_error());
$sql = 'INSERT INTO joke SET
joketext = :joketext,
jokedate = CURDATE()';
$s = $pdo->prepare($sql);
$s->bindValue(':joketext', $_POST['joketext']);
$s->execute();
Well I have a task to store "quotes" into a database (Already done this) and display them & sort them out for the most recent quotes. I'm assuming to get the "most recent", I'd need to store date/time of the submitted quote.
I am new to PHP and trying to learn, so I don't know how to exactly do this.
Here is the PHP for adding the quotes to the database. There are two columns in the table called "quotes" and "id". I'm guessing I will also need to make a column for the date too?
require('includes/connect.php');
$quote = $_POST['quote'];
$quotes = mysql_real_escape_string($quote);
mysql_query("INSERT INTO entries (quote) VALUES('$quotes')")
or die(mysql_error());
How would I also insert the date?
use CURDATE() if you want to insert the current date
example:
$query_auto = "INSERT INTO tablename (col_name, col_date) VALUE ('DATE: Auto CURDATE()', CURDATE() )";
but if you wqant it manually then should use this:
$query_manual = "INSERT INTO tablename (col_name, col_date) VALUES ('DATE: Manual Date', '2008-07-04')";
UPDATE
CREATE TABLE auto_ins
(
`MySQL_Function` VARCHAR(30),
`DateTime` DATETIME,
`Date` DATE,
`Time` TIME,
`Year` YEAR,
`TimeStamp` TIMESTAMP
);
INSERT INTO auto_ins
(`MySQL_Function`, `DateTime`, `Date`, `Time`, `Year`, `TimeStamp`)
VALUES
(“CURDATE()”, CURDATE(), CURDATE(), CURDATE(), CURDATE(), CURDATE());
If you only want the most recent quotes, you can simply sort your result set by their id DESC assuming the id is an auto-incremented value.
Yes, you need a third column lets say most_recent (defined as date or datetime) :
mysql_query("INSERT INTO entries (quote, most_recent) VALUES('$quotes', now())")
You will need at least couple of tables who submitted the quote and the quote table itself.
create table users(id int primary key not null, username varchar(32),pwd varchar(32));
you can add any info to that table like email address and so on.
create table quotes (
id int not null ,
user_id integer,
quote_text varchar(256),
inserted_date timestamp default current_timestamp ,primary key (id));
alter table quotes add constraint fk_users foreign key(user_id) references users(id);
Otherwise feel free to modify them.
It's not about php here its about DB design in general.
Use this code:
require('includes/connect.php');
$quote = $_POST['quote'];
$quotes = now().' - '.mysql_real_escape_string($quote);
// THIS WILL ADD THE DATE AND TIME TO YOUR $quotes STRING.
mysql_query("INSERT INTO entries (quote) VALUES('$quotes')")
or die(mysql_error());