Search code examples
phpmysqlwordpresswordpress-theming

Insert and select data from MySQL in WordPress Page


I am designing a WordPress website, I am through with the design part, now the next phase is the database related things.

  1. Insert data into database.
  2. Select the data and display it in the page.
  3. Where I need to create a PHP page if I don't want to install widget? Where do I need to place the code?

I have googled some plugin and I got php code widget plugin and inserted into one of my pages as a widget

I tried installing insert_php plugin but it's not working so I am continuing with php_code_widget

Pages-> All Pages-> Home Page -> Add Row -> Add Widget -> Php Code Widget.

Now in my MySQL database I have a simple table called Rituals with three columns

 Ritual ID-> Int -> Auto Increment.
 Ritual_Name-> varchar
 Ritual_Active-> varchar.

Now I need to insert the Ritual name to the database, and with some reference I got this code and I have put it in the php code widget window.

<?php
 require_once('../../../wp-load.php');
 function insertuser(){

 if(isset($_POST['submit']){
 global $wpdb;
 $rname=$_POST['rname'];
 $ractive=$_POST['ractive'];
 $table_name = $wpdb->prefix . "mahathiwp";
  $wpdb->insert($table_name, array ('Ritual_Name' => $rname, 'Ritual_Active' =>   $ractive) ); 
 }
 ?>
  <form action="" method="post">
  Ritual Name: <input type="text" name="rname" /><br><br>
  Ritual Active: <input type="text" name="ractive" /><br><br> 
 <input type="submit" name="submit"/>
 </form>

 <?php

 }

insertuser();
?>

Data is not getting inserted.

Can you suggest the proper and faster way to insert the data into the database and also to retrieve the data and show it in my WordPress page. Any help appreciated.


Solution

  • You have to customize your theme,

    Add code to make an action while form is submitted.

    functions.php

    function childtheme_style_andscripts(){
        //wp_enqueue_style('parent-style', get_template_directory_uri() . '/style.css' );
        wp_enqueue_script('ajax-function',  get_stylesheet_directory_uri() . '/js/ajaxfunction.js', array('jquery'), '1.0', true );
        wp_localize_script( 'ajax-function', 'usersubmitform', array(
            'url'=> admin_url('admin-ajax.php'),
            'security'=> wp_create_nonce('our-nonce')
        ) );
    }
    
    add_action('wp_enqueue_scripts','childtheme_style_andscripts');
    
    
    function form_action_function(){
        require_once(dirname( __FILE__ ).'/../../../wp-load.php');
        $data = $_POST['data'];
        global $wpdb;
        if( !check_ajax_referer('our-nonce', 'security' ) ){
    
            wp_send_json_error('security failed');
    
            return;
    
        }
        //var_dump($data);
        $rname=$data['rname'];
        $ractive=$data['ractive'];
    
        $table_name = "rituals";
        $wpdb->insert($table_name, array ('rname' => $rname, 'ractive' => $ractive) ); 
    
        $wpdb->show_errors();
        $wpdb->print_error();
        echo 'From Submitted Successfully';
    
        die();
    }
    add_action('wp_ajax_nopriv_form_action_function','form_action_function');
    add_action('wp_ajax_form_action_function','form_action_function');
    

    Custom Page Template

    <?php
    /**
        Template Name: Form For User
     */
    
    get_header(); ?>
    
    <div id="main-content" class="main-content">
    
    <?php
        if ( is_front_page() && twentyfourteen_has_featured_posts() ) {
            // Include the featured content template.
            get_template_part( 'featured-content' );
        }
    ?>
        <div id="primary" class="content-area">
            <div id="content" class="site-content" role="main">
                <h1 class="headingform">User Form</h1>
                <div class="msg"></div>
                <form  class="userform">
                    Ritual Name: <input type="text" id="rname" name="rname" /><br><br>
                    Ritual Active: <input type="text" id="ractive" name="ractive" /><br><br> 
                    <input  id="usersubmit"type="submit" Value="Submit" />
                </form>
    
            </div><!-- #content -->
        </div><!-- #primary -->
        <?php get_sidebar( 'content' ); ?>
    </div><!-- #main-content -->
    
    <?php
    get_sidebar();
    get_footer();
    

    ajax-admin.js

    Here I have use ajax that why this file is created.put this file into you theme js folder.

    jQuery(document).ready(function($){
    
        var submitButton = document.getElementById('usersubmit');
    
        var ajaxFunctionformprocess = function(fromdata, action){
            $.ajax({
                type:'post',
                url: usersubmitform.url,
                data:{
                    action:action,
                    data:fromdata,
                    security:usersubmitform.security,
    
    
    
                },
                success:function(reponse){
                    $('div.msg').html(reponse);
                },
                error:function(response){
                    alert(response);
                }
    
            });
    
    
    
        }
    
        submitButton.addEventListener('click', function(event){
            event.preventDefault();
            var fromdata = {
                'rname':document.getElementById('rname').value,
                'ractive':document.getElementById('ractive').value,
            };
            ajaxFunctionformprocess(fromdata, 'form_action_function');  
    
            });
    
    
    
    
    });