Kaneda
Kaneda

Reputation: 51

Custom form in WordPress and store values into custom database

I have a simple form with 2 text fields in my WordPress site. I created a new page template and added the following HTML code:

This is the HTML:

<form action="<?php the_permalink(); ?>" id="customform" method="post">
Field 1: <input type="text" name="field1" id="field1">
Field 2: <input type="text" name="field2" id="field2">
<input type="submit" name="submit" id="submit">
</form>

Now all I want to achieve, is that whatever the user inputs, it stores it to mySQL (which is in the same database as WordPress), in the table test_form, for example.

How do I achieve this?

Upvotes: 2

Views: 3569

Answers (2)

Rohil_PHPBeginner
Rohil_PHPBeginner

Reputation: 6080

You can do it by the following code:

<?php
    include_once($_SERVER['DOCUMENT_ROOT'].'/wordpress/wp-config.php');

    $field1 = $_POST['field1'];
    $field2 = $_POST['field2'];
    global $wpdb;
    $wpdb->query(
        $wpdb->prepare("INSERT INTO wp_test_form ( field1, field2 ) 
            VALUES ( %d, %d)",$field1,$field2)
    );      
?>

NOTE: Tested with table called wp_test_form. You can add your own table name. It is for integer value.If you want string then change %d to %s.

Upvotes: 5

user3767121
user3767121

Reputation:

Try this, it will help you.

  $field1   =   $_POST['field1'];
  $field2    =   $_POST['field2'];
  $page_one_table = 'test_form';
  $page_one_inputs =  array(
  'field1' => $field1,
  'field2' => $field2
  );
//  Insert the data into a new row
  $insert_page_one  =   $wpdb->insert($page_one_table, $page_one_inputs);
  //    Grab the ID of the row we inserted for later use
$form_id = $wpdd->insert_id;

Upvotes: 1

Related Questions