0

I'm currently developing a small portal on Wordpress for a client where users have to submit forms (created with Gravity Forms). I'd like to be able to store the data from these forms, upon submission, onto a custom database that I created on phpmyadmin. I have all the tables and structure set up, but I don't know how to feed the data through.

I know I eventually have to use the 'gform_after_submission' hook, I just don't know where to start.

Thanks!

0

You can use something like below. Basically after form submission we get the data $entry extract the values we want (in the example $val1, $val2, $val3) then insert that data into the custom table with $wpdb:

add_action('gform_after_submission', 'save_to_my_custom_table', 10, 2);
function save_to_my_custom_table($entry, $form)
{
  global $wpdb;

  // update for your tablename (this assumes the table lives in same database as the other wp tables)
  $tablename = $wpdb->prefix . "my_custom_tablename";

  // grab from values from the entry
  $val1 = rgar( $entry, '1' );
  $val2 = rgar($entry, '2');
  $val3 = rgar($entry, '3');

  // basic insert
  $sql = "INSERT INTO `$tablename` (`val1`,`val1`, `val1`) values (%s, %s, %d)";

  // use a prepared statement
  $stmt = $wpdb->prepare($sql, $val1, $val2, $val3);

  // run the query
  $wpdb->query($stmt);
}

If you are wanting to connect to a database totally outside the WP app I think you might want to consider setting up an API for communicating between the two. In that case you can still approach this very similary. See below:

add_action('gform_after_submission', 'save_to_my_custom_table', 10, 2);
function save_to_my_custom_table($entry, $form)
{
  global $wpdb;

  // update for your tablename (this assumes the table lives in same database as the other wp tables)
  $tablename = $wpdb->prefix . "my_custom_tablename";

  // grab from values from the entry
  $val1 = rgar( $entry, '1' );
  $val2 = rgar($entry, '2');
  $val3 = rgar($entry, '3');

  // send POST reqest to API for other database
  $endpoint = 'api.example.com';

  $body = [
      'val1'  => $val1,
      'val2'  => $val2,
      'val3'  => $val3,
  ];

  $body = wp_json_encode( $body );

  $options = [
      'body'        => $body,
      'headers'     => [
          'Content-Type' => 'application/json',
      ],
      'timeout'     => 60,
      'redirection' => 5,
      'blocking'    => true,
      'httpversion' => '1.0',
      'sslverify'   => false,
      'data_format' => 'body',
  ];

  wp_remote_post( $endpoint, $options );
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.