Simple form that saves to database

For what I can understand you already have the table in your database.

I don’t know how you have named it, but a best practise (for me a must-do practise) is to name it with the same table prefix of wordpress, that’s the one setted in wp-config.php.

You also don’t say how this table is structured, but I guess it’s somethimg like:

ID (integer,primary,autoincrement) | name (varchar) | phone (varchar) | email (varchar)

You can add a shortcode that print the form. In your functions.php add:

add_action('init', function() {
  add_shortcode('userform', 'print_user_form');
});

function print_user_form() {
  echo '<form method="POST">';
  wp_nonce_field('user_info', 'user_info_nonce', true, true);
  ?>

  All your form inputs (name, email, phone) goes here.  

<?php
  submit_button('Send Data');
  echo '</form>';
}

Now just create a post or a page in wp dashboard and simply add [userform]: the form is magically printend in the page.

As you can see I’ve not added the action attribute to form, in this way the form send post data to same page.

Now you have to save data. add an action on a early hook, look for the $_POST, check the nonce and save your data:

add_action('template_redirect', function() {
   if ( ( is_single() || is_page() ) &&
        isset($_POST[user_info_nonce]) &&
        wp_verify_nonce($_POST[user_info_nonce], 'user_info')
    ) {
      // you should do the validation before save data in db.
      // I will not write the validation function, is out of scope of this answer
      $pass_validation = validate_user_data($_POST);
      if ( $pass_validation ) {
        $data = array(
          'name' => $_POST['name'],
          'email' => $_POST['email'],
          'phone' => $_POST['phone'],
        );
        global $wpdb;
        // if you have followed my suggestion to name your table using wordpress prefix
        $table_name = $wpdb->prefix . 'my_custom_table';
        // next line will insert the data
        $wpdb->insert($table_name, $data, '%s'); 
        // if you want to retrieve the ID value for the just inserted row use
        $rowid = $wpdb->insert_id;
        // after we insert we have to redirect user
        // I sugest you to cretae another page and title it "Thank You"
        // if you do so:
        $redirect_page = get_page_by_title('Thank You') ? : get_queried_object();
        // previous line if page titled 'Thank You' is not found set the current page
        // as the redirection page. Next line get the url of redirect page:
        $redirect_url = get_permalink( $redirect_page );
        // now redirect
        wp_safe_redirect( $redirect_url );
        // and stop php
        exit();
      }
   }
});

The code is rough, but should be a valid starting point. Inline comments should help you to understand the workflow.

Be sure to read the documents:

Leave a Comment