简体   繁体   中英

What's the correct way of inserting data into a mysql table using wordpress?

I have to insert a text value, a date and an enum, example:

email -> varchar(256),
date -> datetime,
subscribed -> enum('yes', 'no')

I've written the code bellow, but I'm not really sure what's the correct way of inserting, like the formats, is datetime a string or not, etc. I don't get any error in wordpress so it's kinda hard for me to tell where I am wrong.

if(isset($_POST['newsletter_submit'])) {
  $email = $_POST['email'];
  $sql = $wpdb->prepare(
     "INSERT INTO `wp_newsletter` (`email`,`date`, 'subscribed') values (%s,%s,%s)",
      $email, current_time('mysql'), 'yes');

  $wpdb->query($sql);
}

You can use $wpdb->show_errors() to see error. For inserting data to database you should use $wpdb->insert($table, $data, $format) method. Your code can be written like this:

$wpdb->insert(`wp_newsletter`,
              array (
                  'email'      => $email,
                  'date'       => date("F j, Y \a\t g:ia"),
                  'subscribed' => 'yes'
              ), //Data should be raw. They're validated by giving their type as third argument
              array ('%s', '%s', '%s'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM