Search code examples
mysqlwordpresswampservercontact-formninja-forms

Contcatform7 or Ninja form data store in custom database table - Wordpress


I use both Ninja Form and Contact Form 7 to access user input. But the problem I face is that the submission get stored in default tables(wp_post and wp_metapost). I feel it inconvenient to access the entered submission. So I wanted to store the submission into my user defined table in the same db. How can I do that?

I'm using a wordpress site with Ninja form (contact form 7 is also fine), Mysql local wamp server.


Solution

  • Kindly check below steps how you can add data in custom database table.

    1) Create database table using following query

    CREATE TABLE contactfordata(
    id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(50)
     );
    

    2) Create contact form 7 form with following field

    [text* name] 
    [submit "Send"]
    

    3) Add following code in fucntions.php file

     remove_all_filters ('wpcf7_before_send_mail');
     add_action( 'wpcf7_before_send_mail', 'before_send_mail_contactform7' );  
    
     function before_send_mail_contactform7( $formdata_db ) 
    {
    
       $mydb_CUSTOM = new wpdb('DB_USERNAME','DB_PASSWORD','DB_NAME','HOST_NAME'); // add db detail here
    
       $formdata_db = WPCF7_Submission::get_instance();
    
      if ( $formdata_db ) 
        $formData = $formdata_db->get_posted_data();
    
      $name = $formData['name']; // set form data in variable
    
       $mydb_CUSTOM->insert( 'contactfordata', array( 'name' =>$name ), array( '%s' ) ); // insert the data in your custom table.
    }
    

    This will work for you code is tested.