How to insert data using wpdb
Solution 1:
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.
Solution 2:
Just use wpdb->insert(tablename, coloumn, format)
and wp will prepare that's query
<?php
global $wpdb;
$wpdb->insert("wp_submitted_form", array(
"name" => $name,
"email" => $email,
"phone" => $phone,
"country" => $country,
"course" => $course,
"message" => $message,
"datesent" => $now ,
));
?>
Solution 3:
Try this
I recently leaned about $wpdb->prepare
HERE and added into our Free Class Booking plugin, plugin approved on wordpress.org and will live soon:
global $wpdb;
$tablename = $wpdb->prefix . "submitted_form";
$name = "Kumkum"; //string value use: %s
$email = "[email protected]"; //string value use: %s
$phone = "3456734567"; //numeric value use: %d
$country = "India"; //string value use: %s
$course = "Database"; //string value use: %s
$message = "hello i want to read db"; //string value use: %s
$now = new DateTime(); //string value use: %s
$datesent = $now->format('Y-m-d H:i:s'); //string value use: %s
$sql = $wpdb->prepare("INSERT INTO `$tablename` (`name`, `email`, `phone`, `country`, `course`, `message`, `datesent`) values (%s, %s, %d, %s, %s, %s, %s)", $name, $email, $phone, $country, $course, $message, $datesent);
$wpdb->query($sql);
Thanks -Frank
Solution 4:
The recommended way (as noted in codex):
$wpdb->insert( $table_name, array('column_name_1'=>'hello', 'other'=> 123), array( '%s', '%d' ) );
So, you'd better to sanitize values - ALWAYS CONSIDER THE SECURITY.
Solution 5:
You have to check your quotes
properly,
$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);
OR you can use like,
$sql = "INSERT INTO `wp_submitted_form`
(`name`,`email`,`phone`,`country`,`course`,`message`,`datesent`)
values ($name, $email, $phone, $country, $course, $message, $datesent)";
$wpdb->query($sql);
Read http://codex.wordpress.org/Class_Reference/wpdb