2

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?

2
  • can you provide the test_form table layout? there is a good example here w3schools.com/php/php_mysql_insert.asp Commented Oct 6, 2014 at 7:11
  • The table layout for test_form is simply Field1 (VARCHAR), Field2 (VARCHAR). Commented Oct 6, 2014 at 7:28

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

You wrote "If you want string then change %d to %s". What happenes if it is a date format?
Also, if when you submit the form, it adds 2 additional blank rows into the database. How can I fix this? Thanks :)
1

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.