Hey everyone, I’m trying to add the current date and time when inserting data into a WordPress database table. I’ve been using $wpdb->insert()
, but I can’t seem to get the MySQL NOW()
function to work. Here’s what I’ve tried:
$info = array(
'record_id' => NULL,
'customer_data' => serialize($_POST['customer']['Info']),
'timestamp' => NOW(),
'customer_id' => $logged_in_user->ID
);
$wpdb->insert(CUSTOMER_TABLE, (array) $info);
The NOW()
part doesn’t seem to be working. Is there a way to use the current timestamp with $wpdb->insert()
? Or do I need to use a different approach? Any help would be appreciated!
I’ve encountered this issue before, and there’s a simple solution. Instead of using NOW() directly, you need to use the current_time() function provided by WordPress. Here’s how you can modify your code:
$info = array(
'record_id' => NULL,
'customer_data' => serialize($_POST['customer']['Info']),
'timestamp' => current_time('mysql'),
'customer_id' => $logged_in_user->ID
);
$wpdb->insert(CUSTOMER_TABLE, (array) $info);
The current_time(‘mysql’) function returns a MySQL-formatted datetime string, which is exactly what you need for your timestamp column. This approach ensures that you’re using the WordPress-configured timezone, maintaining consistency across your site.
I’ve dealt with this exact situation in a recent project. While the suggestions above work, I found a more elegant solution using WordPress’s built-in functions. Try this approach:
$info = array(
'record_id' => NULL,
'customer_data' => serialize($_POST['customer']['Info']),
'timestamp' => gmdate('Y-m-d H:i:s'),
'customer_id' => $logged_in_user->ID
);
$wpdb->insert(CUSTOMER_TABLE, $info);
Using gmdate() ensures you’re always working with UTC time, which is generally best practice for database timestamps. It avoids potential timezone issues and integrates seamlessly with $wpdb->insert(). Just remember to convert the timestamp to the desired timezone when displaying it to users.
Also, note that you don’t need to cast $info to an array - $wpdb->insert() already expects an array as its second parameter. This small optimization can help keep your code cleaner.
hey mate, i had the same problem. try using PHP’s date() function instead. it’s easy:
'timestamp' => date('Y-m-d H:i:s'),
this’ll give u the current date/time in mysql format. works like a charm with $wpdb->insert(). hope this helps!