简体   繁体   中英

Inserting data into wordpress table using a html form

I am trying for hours to resolve what I thought was a simple issue but am still no further...

Below is my code to input 3 fields into a wordpress custom table called 'std'. Not sure if it is a connection issue or my code is just wrong! when I click submit, the I am just given the "databse insertion failed" message but am not the wiser as to why.

<?php

   /*
   Template Name:ProRata
   */

   //get_header();

    if($_POST['Submit']){


    global $wpdb;

    require_once('wp-config.php');

    $name=$POST['aname'];
    $roll=$POST['aroll'];
    $dept=$POST['adept'];

    $tablename = $wpdb->prefix.'std';

    if($wpdb->insert(
    $tablename,

    array(


    'name'=> $name,
    'roll'=> $roll,
    'dept'=> $dept
    )


    ) ==false) wp_die('databse insertion failed');
    else echo 'Database insertion completed</p>';

    ?>
    <?php
    }
    else // if form has not yet been submitted
    {
    ?>
    <br>

    <form action="" method="post">
    <label>Leave: Type of leave </label>

    <label> aname </label>
    <input type="text" name="aname"><br><br>
    <label> Leave: Start Date </label>
    <input type="text" name="aroll"><br><br>
    <label> Leave: End Date </label>
    <input type="text" name="adept"><br><br>
    <input type="submit" name="Submit"><br>

    </form>
    <?php

    }

    ?>

I am not sure if this will totally resolve your issue, but you are missing the underscores ( _ ) when you are storing the $_POST values. You need to change those lines to the following:

$name=$_POST['aname'];
$roll=$_POST['aroll'];
$dept=$_POST['adept'];

finally got the answer....

Change this
$name=$POST['aname'];
$roll=$POST['aroll'];
$dept=$POST['adept'];

$tablename = $wpdb->prefix.'std';

With this
$name=$_POST['aname'];
$roll=$_POST['aroll'];
$dept=$_POST['adept'];

$tablename = 'std';

Error on insertion is because it's trying to insert into table "wp_std", assuming that the prefix on your wordpress is wp_, or any prefix. Also I changed $POST with $_POST, because even if insertion where true, it would insert empty values because $POST doesnt exists unleast you declare it, correct global variable is $_POST

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM