Error on inserting a form value to database

You’re posting directly to formaction.php, as such WordPress is never loaded and so you do not have access to any of its API, including the database API stored in global $wpdb (which is causing the error). I’d recommend keeping everything in WordPress… and a useful method for form handling is using admin-post.php (if you’re familiar with WordPress’ ajax handling – this is a similar idea).

The idea is that you post to the url

 .../wp-admin/admin-post.php

which you can get via admin_url('admin-post.php');. And you post – along with any data and nonces – a unique value for the action variable. (Let’s say wpse111797_form_submitted). When the form is submitted to admin-post.php, WordPress will trigger the hook:

  • admin_post_wpse111797_form_submitted – if you are logged in
  • admin_post_nopriv_wpse111797_form_submitted – if you are logged out

So your form might look like:

<form action="<?php echo admin_url('admin-post.php'); ?>" method="post">
    <input type="hidden" name="action" value="wpse111797_form_submitted">

    <input type="text" name="name1" value="">
    <input type="text" name="name2" value="">

    <input type="submit" name="submit" value="add">

</form>

Please don’t forget to uses nonces to verify intent.

You can then hook onto either of the above hooks (or both) depending on whether you want to handle form submissions from logged in users, guests, or both.

function wpse111797_form_handler(){

   global $wpdb;
   $name1 = isset( $_POST['name1'] ) ? $_POST['name1'] : null;
   $name2 = isset( $_POST['name2'] ) ? $_POST['name2'] : null;

   //TODO Check nonces & permissions first!

   $my_table_name=$wpdb->prefix."my_table";

   $rows_affected = $wpdb->insert( $my_table_name, array( 'first' => $name1, 'last' => $name2 ) );

   //Redirect user to a 'success' page, or from back whence they came!
}

//Attach callback to hook (in this case, the hook for logged-in users)
add_action( 'admin_post_wpse111797_form_submitted', 'wpse111797_form_handler' );