Amit

How to insert contact form 7 data into mysql database in wordpress

First you need to Create a table and add fields example “contacts” and table fields are below

id , form_id, first_name, last_name, email_id, phone_no, subject, message, date

if you not able to create any table. just copy the below code and pest in to your functions.php file


function ab_create_table_contact_form() {

global $wpdb;
$table_name = $wpdb->prefix. "contacts";
global $charset_collate;
$charset_collate = $wpdb->get_charset_collate();
global $db_version;

if( $wpdb->get_var("SHOW TABLES LIKE '" . $table_name . "'") != $table_name)
{ 
$create_sql = "CREATE TABLE " . $table_name . " (
id INT(11) NOT NULL auto_increment,
form_id int(11) NOT NULL,
first_name VARCHAR(255) NOT NULL,
last_name VARCHAR(255) NOT NULL,
email_id VARCHAR(255) NOT NULL,
phone_no int(11) NOT NULL,
subject VARCHAR(255) NOT NULL,
message TEXT NOT NULL,
date datetime NOT NULL DEFAULT current_timestamp()

PRIMARY KEY (id))$charset_collate;";
require_once(ABSPATH . "wp-admin/includes/upgrade.php");
dbDelta( $create_sql );
}

//register the new table with the wpdb object
if (!isset($wpdb->contacts))
{
$wpdb->reviews = $table_name;
//add the shortcut so you can use $wpdb->stats
$wpdb->tables[] = str_replace($wpdb->prefix, '', $table_name);
}

}
add_action( 'init', 'ab_create_table_contact_form');

 

after that now just copy below code and pest in to your functions.php file

add_action('wpcf7_before_send_mail', 'ab_before_send_mail' );

function ab_before_send_mail($form_tag) {
    global $wpdb;
    $table_name = $wpdb->prefix.'contacts';

    $submission = WPCF7_Submission::get_instance();
    $contact_form = $submission->get_contact_form();

    if ($submission) {

        $form_data = $submission->get_posted_data();

        $form_id = $form_tag->id();
        $first_name = $form_data['first-name'];
        $last_name = $form_data['last-name'];
        $email_id = $form_data['your-email'];
        $phone_no = $form_data['phone-number'];
        $subject = $form_data['your-subject'];
        $message = $form_data['your-message'];
        $form_date = current_time('Y-m-d H:i:s');

        $data = array(
    	   'form_id' => $form_id,
           'first_name' => $first_name,
           'last_name' => $last_name,
           'email_id' => $email_id,
           'phone_no' => $phone_no,
           'subject' => $subject,
           'message' => $message,
           'date' => $form_date
        );

        $wpdb->insert( $table_name, $data);

	}
}

Last Update on:January 7th, 2024 at 6:09 pm


How to get current page slug and post slug
Previous post