简体   繁体   中英

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.

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('Ymd 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!

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

尝试将PHP time()用作纪元时间戳

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM