Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress - $wpdb->insert - MySQL NOW()

Tags:

wordpress

is there any possibility to use the MySQL NOW() in the $wpdb->insert call?

When I use the following code, NOW() is not working.

$data = array(         'id' => NULL,         'order' => serialize($_POST['data']['Order']),         'created' => NOW(),         'user_id' => $current_user->ID     );  $wpdb->insert(ORDERS_TABLE, (array) $data ); 
like image 706
chris Avatar asked Dec 19 '11 19:12

chris


People also ask

How do I insert WordPress data into Wpdb?

Use $wpdb->insert() . $wpdb->insert('wp_submitted_form', array( 'name' => 'Kumkum', 'email' => '[email protected]', 'phone' => '3456734567', // ... and so on )); Addition from @mastrianni: $wpdb->insert sanitizes your data for you, unlike $wpdb->query which requires you to sanitize your query with $wpdb->prepare .

What does Wpdb -> insert return?

This answer is useful. This answer is not useful. Show activity on this post. $wpdb->insert() method returns false if the row could not be inserted. Otherwise, it returns the number of affected rows (which will always be 1).

How do I print a insert query in WordPress?

Print Executed SQL in WordPress To print sql queries in wordpress we use $wpdb object. The $wpdb object has some properties for this. Using $wpdb->last_query to print just the latest query executed, this is useful for debugging functions. Using a plugin like Query Monitor.


2 Answers

I believe the canonical approach is to use the WordPress current_time() function passing it 'mysql' as the first parameter to specify a mysql timestamp compatible format (the alternative is UNIX timestamp format) and '1' as the second parameter to specify GMT time (default is local), like this:

$data = array(     'id' => NULL,     'order' => serialize($_POST['data']['Order']),     'created' => current_time('mysql', 1),     'user_id' => $current_user->ID );  $wpdb->insert(ORDERS_TABLE, $data); 

current_time('mysql', 1) outputs 2012-07-18 12:51:13.

More here: http://codex.wordpress.org/Function_Reference/current_time

like image 173
coderabbi Avatar answered Sep 28 '22 13:09

coderabbi


For anyone using Wordpress 5.3 and above, the recommended approach is to now use wp_date, not current_time.

wp_date('Y-m-d H:i:s'); 
like image 33
gbones Avatar answered Sep 28 '22 14:09

gbones