How to Save Form Data to WordPress Database Securely

How to save form data in wordpress database; Save contact form data to wordpress database; Store wordpress form data in mysql; Wordpress save form submissions to database; Best plugin to save form data in wordpress; Wordpress database form data storage; How to store form entries in wordpress; Wordpress form data to database tutorial; Save wpforms data to database; Wordpress form data storage solution;

Explanation

Here's a simple way to save form data into your WordPress database using a custom solution. This code handles form submissions and stores the data securely.

  • Form Submission Hook: The code listens for form submissions using WordPress's AJAX actions. This means it can handle form data without refreshing the page.
  • Security Check: It uses a nonce (a unique token) to ensure the form submission is secure and genuine. This helps prevent unauthorized submissions.
  • Data Sanitization: Before saving, the form data is cleaned up to remove any unwanted characters. This includes sanitizing text fields, emails, and text areas.
  • Email Validation: The code checks if the email provided is valid. If not, it sends an error message back to the user.
  • Database Insertion: The sanitized data is then inserted into a custom database table called form_submissions. If successful, a success message is returned; otherwise, an error message is sent.
  • Table Creation: When the plugin or theme is activated, a new table is created in the database to store the form submissions. This ensures there's a dedicated space for your data.
  • Script Enqueueing: The necessary JavaScript file is loaded to handle the form submission via AJAX. It also passes the AJAX URL and nonce to the script for secure communication.

This setup allows you to efficiently store form data in your WordPress database, providing a custom solution without relying on third-party plugins.

Code

<?php
// Hook into the form submission action
add_action('wp_ajax_wp_dudecom_save_form_data', 'wp_dudecom_save_form_data');
add_action('wp_ajax_nopriv_wp_dudecom_save_form_data', 'wp_dudecom_save_form_data');

// Function to handle form data saving
function wp_dudecom_save_form_data() {
    // Check for nonce security
    check_ajax_referer('wp_dudecom_form_nonce', 'security');

    // Sanitize and validate form data
    $name = sanitize_text_field($_POST['name']);
    $email = sanitize_email($_POST['email']);
    $message = sanitize_textarea_field($_POST['message']);

    // Validate email
    if (!is_email($email)) {
        wp_send_json_error('Invalid email address');
    }

    global $wpdb;
    $table_name = $wpdb->prefix . 'form_submissions';

    // Prepare data for insertion
    $data = array(
        'name' => $name,
        'email' => $email,
        'message' => $message,
        'submitted_at' => current_time('mysql')
    );

    // Insert data into the database
    $inserted = $wpdb->insert($table_name, $data);

    if ($inserted) {
        wp_send_json_success('Form data saved successfully');
    } else {
        wp_send_json_error('Failed to save form data');
    }

    wp_die();
}

// Create the database table on plugin/theme activation
function wp_dudecom_create_form_table() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'form_submissions';

    $charset_collate = $wpdb->get_charset_collate();

    $sql = "CREATE TABLE $table_name (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        name tinytext NOT NULL,
        email text NOT NULL,
        message text NOT NULL,
        submitted_at datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
        PRIMARY KEY  (id)
    ) $charset_collate;";

    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
}
register_activation_hook(__FILE__, 'wp_dudecom_create_form_table');

// Enqueue necessary scripts
function wp_dudecom_enqueue_scripts() {
    wp_enqueue_script('wp-dudecom-form-handler', get_template_directory_uri() . '/js/form-handler.js', array('jquery'), null, true);
    wp_localize_script('wp-dudecom-form-handler', 'wp_dudecom_ajax', array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'nonce' => wp_create_nonce('wp_dudecom_form_nonce')
    ));
}
add_action('wp_enqueue_scripts', 'wp_dudecom_enqueue_scripts');
?>

Instructions

To implement the code for saving form data to the database, follow these steps:

File Location: Add the code to your theme's functions.php file or create a custom plugin file.

Prerequisites:

  • Ensure you have access to your WordPress site's file system.
  • Basic understanding of WordPress file structure and PHP.

Implementation Steps:

  1. Open your theme's functions.php file: Navigate to wp-content/themes/your-theme/functions.php using a file manager or FTP client.
  2. Copy and paste the provided code: Insert the entire code snippet into the functions.php file or your custom plugin file.
  3. Create the JavaScript file: In your theme directory, create a js folder if it doesn't exist. Inside it, create a file named form-handler.js.
  4. Add AJAX form submission logic: In form-handler.js, add JavaScript to handle form submissions using AJAX. Ensure it sends data to the wp_dudecom_save_form_data action.
  5. Activate the plugin (if applicable): If you added the code to a custom plugin, activate the plugin from the WordPress admin dashboard under Plugins.
  6. Test the form: Create a form on your site that includes fields for name, email, and message. Ensure the form submits data via AJAX to the specified action.
  7. Verify database entries: Check your WordPress database to ensure the form_submissions table is created and data is being inserted correctly.

This setup allows you to efficiently store form data in your WordPress database, providing a custom solution without relying on third-party plugins.

If you need help with implementation or more advanced functionality, consider using the services of wp-dude.com.