How to store values from WP Forms into an external remote Database

Posted by George Nicolaou

On 12 May, 2022
George Nicolaou - Senior Web Developer

Code I used on websquadronapi.local which is where WP Forms and WordPress are installed

function wpf_george_process_complete( $fields, $entry, $form_data, $entry_id ) { 
 // Optional, you can limit to specific forms. Below, we restrict output to
 // form #5.
 if ( absint( $form_data['id'] ) !== 5 ) {
 return;
 } 
 // Get the full entry object
 $entry = wpforms()->entry->get( $entry_id ); 
 // Fields are in JSON, so we decode to an array
 $entry_fields = json_decode( $entry->fields, true );
 // get the first name and email as a string
 $FullName = $entry_fields['1']['value'];
 $Email = $entry_fields['2']['value'];
 // Convert back to json
 $entry_fields = json_encode( $entry_fields );
 // Save changes
 wpforms()->entry->update( $entry_id, array( 'fields' => $entry_fields ), '', '', array( 'cap' => false ) );
 //magic time start  if( ! $FullName  || ! $Email ){
 error_log( 'Unable to get userdata!' );
 return;
 }
 $body = array( 
 'FullName' => $FullName,
 'Email'     => $Email
 );
 $url  = 'https://georgiosn39.sg-host.com/savedata.php?FullName='.$FullName.'&Email='.$Email; 
 $args = array(
 'method'      => 'POST',
 'timeout'     => 45,
 'sslverify'   => false,
 'headers'     => array(
 //'Authorization' => 'Bearer {token goes here}',
 'Content-Type'  => 'application/json',
 ),
 'body'        => $body,
 );
 $request = wp_remote_post( $url, $args );
 if ( is_wp_error( $request ) || wp_remote_retrieve_response_code( $request ) != 200 ) {
 error_log( print_r( $request, true ) );
 }
 $response = wp_remote_retrieve_body( $request );
 //console_log($response);
//magic time end
}
add_action( 'wpforms_process_complete', 'wpf_george_process_complete', 10, 4 );

Code I used in savedata.php on remote server

<?php
$servername = "localhost";
$username = "random";
$password = "whatever";
$dbname = "dbnamewhatever";
$FullName = $_GET['FullName'];
$Email = $_GET['Email'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
 die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO Subs (id, FullName, Email)
VALUES ('', '$FullName', '$Email')";
if ($conn->query($sql) === TRUE) {
 echo "New record created successfully";
} else {
 echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>

You may also like…

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

Pin It on Pinterest

Share This
Divi Theme Code SnippetsHow to store values from WP Forms into an external remote Database