GRS
GRS

Reputation: 3084

PHP/SQL create a date stamp and insert it into database

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.

Upvotes: 0

Views: 323

Answers (3)

odan
odan

Reputation: 4952

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');
}

Upvotes: 1

Nick
Nick

Reputation: 906

try PHP time() for epoch timestamp

Upvotes: -1

Ajay Gupta
Ajay Gupta

Reputation: 2033

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!

Upvotes: 1

Related Questions