Inserting data into custom tables

You said your form is in the main folder? I guess you need to set proper URL for action="". You could try:

action="<?php echo site_url() . '/setLiquorType.php'; ?>"

It is best practice to put your form code into functions.php and then leave form action=”” empty. Then you can trigger your form function when the form is submitted.

Your Form HTML:

<form method = "post" action = ""> //edited form action
     
      <h3>Add a New Liquor Type</h3> //wrapped title with <h3> tags and removed <br> because h3 element will have padding that will separate it from form (if not provided in your style.css it will be assigned by the browser)
      <p>  //wraping field with paragraph to generate automatic space between them without styling it
         <label for="name">Name:</label>  //removed <p> element and used <label> instead
         <input type="text" name="name"/>
      </p>
      <p>
         <label for="description">Description</label>
         <input type="text" name="description"/>
      </p>
      <hr> //replaced unnecessary --- lines 
      <input type="submit" value="Submit" name="liquor_submit"/>  // added name attribute that will be used to check if the form is submitted
</form>
</br>

Now in your functions.php you can add something like:

//setting up the form
function themename_add_new_liquor() {
    
    $name         = $_POST['name'];
    $description  = $_POST['description'];  //You forgot to collect data from "description" field
    
    global $wpdb; //removed $name and $description there is no need to assign them to a global variable
    $table_name = $wpdb->prefix . "liquor_type"; //try not using Uppercase letters or blank spaces when naming db tables

    $wpdb->insert($table_name, array(
        'lq_name' => $name, //replaced non-existing variables $lq_name, and $lq_descrip, with the ones we set to collect the data - $name and $description
        'description' => $description
    ),
    array(
        '%s',
        '%s'
    ) //replaced %d with %s - I guess that your description field will hold strings not decimals
    );
}

//And now to connect the  two:  
if( isset($_POST['liquor_submit']) ) themename_add_new_liquor();

I hope this can help. Also, none of this will work if you have not created your Database table in the first place ( $wpdb->insert function is used for inserting data in the existing table ).

Leave a Comment