如何使用 wpdb 插入数据

2022-08-30 10:47:02

我写得如下

$name="Kumkum";
$email="kumkum@gmail.com";
$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);

它不起作用...它抛出错误...请帮我纠正它。


答案 1

用。$wpdb->insert()

$wpdb->insert('wp_submitted_form', array(
    'name' => 'Kumkum',
    'email' => 'kumkum@gmail.com',
    'phone' => '3456734567', // ... and so on
));

@mastrianni的补充:

$wpdb->insert为您清理数据,这与要求您使用 清理查询不同。两者之间的区别在于允许您编写自己的SQL语句,其中接受数组并为您处理清理/ sql。$wpdb->query$wpdb->prepare$wpdb->query$wpdb->insert


答案 2

只需使用,wp将准备该查询wpdb->insert(tablename, coloumn, format)

<?php
global $wpdb;
$wpdb->insert("wp_submitted_form", array(
   "name" => $name,
   "email" => $email,
   "phone" => $phone,
   "country" => $country,
   "course" => $course,
   "message" => $message,
   "datesent" => $now ,
));
?>

推荐