plugins – How can I insert a record into a custom table from my custom form in my custom admin page?

Question

I’m struggling with this one and all of the relevant links to the codex, articles and forum posts (stack or otherwise) that I’ve searched haven’t helped.

I can best describe my problem as attempting to replicate the native “Add New User” WordPress functionality. I.e. render a form from an admin page, insert a new record from this form (the equivalent of adding a new user) and update the table.

So far I have:

Add Episodes Form

The plugin code so far looks like:

<?php
    /*

    Plugin Name: Episodes

    Description: The episodes plugin

    Author: Nick Courage

    Version: 1.0

    */

    function activate_episodes(){

        global $wpdb;

        $table_name = $wpdb->prefix . 'episodes';

        if($wpdb->get_var('SHOW TABLES LIKE' . $table_name) != $table_name){

            $sql="CREATE TABLE " . $table_name . '(

                episode_id INT NOT NULL AUTO_INCREMENT,

                episode_title VARCHAR(45) NOT NULL,

                episode_desc VARCHAR(45) NOT NULL,

                air_date DATE NOT NULL,

                img_url VARCHAR(255) NOT NULL,

                PRIMARY KEY (episode_id)

                )';

    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');

    dbDelta($sql);

    add_option('episode_database_version', '1.0');

    }
    }

    register_activation_hook(__FILE__,'activate_episodes');

    function episodes_add_page(){

        ?>
        <h1>Add Episodes</h1>
        <form method="$_POST" action="">
            <label for="episode_title">Episode Title:</label>
            <input type="text" name="episode_title" id="episode_title" />
            <label for="episode_desc">Episode Description:</label>
            <input type="text" name="episode_desc" id="episode_desc" />
            <label for="air_date">Air date:</label>
            <input type="text" name="air_date" id="air_date" />
            <input type="submit" value="Submit"/>
        </form>


        <?php

    }

    function episodes_plugin_menu(){

        add_menu_page('Episodes Page', 'Episodes', 'manage_options','episodes-plugin','episodes_add_page');

    }

    add_action('admin_menu','episodes_plugin_menu');




    function add_episode(){

        global $wpdb;

        $table_name = $wpdb->prefix . 'episodes';

        $wpdb->insert($table_name, array('episode_title'=>$_POST['episode_title'],

            'episode_desc'=>$POST['episode_desc'],

            'air_date'=>$_POST['air_date'],

            'img_url'=>$_POST['img_url']

            )

        );

    }

    ?>

0
NickC 6 years 2015-07-05T12:03:00-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse