Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert data using wpdb

Tags:

php

wordpress

I have wriiten as following

$name="Kumkum"; $email="[email protected]"; $phone="3456734567"; $country="India"; $course="Database"; $message="hello i want to read db"; $now = new DateTime(); $datesent=$now->format('Y-m-d H:i:s');     global $wpdb; $sql = $wpdb->prepare(  "INSERT INTO `wp_submitted_form`      (`name`,`email`,`phone`,`country`,`course`,`message`,`datesent`) values ("  $name, $email, $phone, $country, $course, $message, $datesent. ')")';  $wpdb->query($sql); 

It's not working... It throws error... Please help me in correcting it.

like image 600
Nida Avatar asked Aug 07 '13 06:08

Nida


1 Answers

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. The difference between the two is $wpdb->query allows you to write your own SQL statement, where $wpdb->insert accepts an array and takes care of sanitizing/sql for you.

like image 86
Nadh Avatar answered Oct 02 '22 11:10

Nadh