Friday, November 18, 2022

Wordpress crud frontend side

 Hello. Today I saw you how to create crud in user frontend side. 


Plugin Folder name : frontend-crud

Filename : frontend-crud.php

Code:-

<?php

/*

 * Plugin Name: Frontend CRUD

 * Description: Frontend crud functionality.

 * Version: 1.0

 * Author: Chirag

 * Plugin URI: #

 * Author URI: #

 */


register_activation_hook(__FILE__, 'table_creator');

function table_creator()

{

    global $wpdb;

    $charset_collate = $wpdb->get_charset_collate();

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

    $sql = "DROP TABLE IF EXISTS $table_name;

            CREATE TABLE $table_name(

            id mediumint(11) NOT NULL AUTO_INCREMENT,

            emp_id varchar(50) NOT NULL,

            emp_name varchar (250) NOT NULL,

            emp_email varchar (250) NOT NULL,

            emp_dept varchar (250) NOT NULL,

            PRIMARY KEY id(id)

            )$charset_collate;";

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

    dbDelta($sql);

}


//[frontend_crud]

add_shortcode('frontend_crud','da_ems_frontend_crud_callback');



function da_ems_frontend_crud_callback(){


    global $wpdb;

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

    $msg = '';

    if(@$_REQUEST['action'] == 'submit'){

        $wpdb->insert("$table_name", [

            'emp_id' => sanitize_text_field($_REQUEST['emp_id']),

            'emp_name'=> sanitize_text_field($_REQUEST['emp_name']),

            'emp_email'=> sanitize_email($_REQUEST['emp_email']),

            'emp_dept'=> sanitize_text_field($_REQUEST['emp_dept']),

        ]);


        if($wpdb->insert_id > 0){

            $msg = "Saved Successfully";

        }else{

            $msg = "Failed to save data";

        }

    }


    if(@$_REQUEST['action'] == 'update-emp' && @$_REQUEST['id']){

        $id = @$_REQUEST['id'];

        if(@$_REQUEST['emp_id'] && @$_REQUEST['emp_name'] && @$_REQUEST['emp_email'] && @$_REQUEST['emp_dept']){

            $update = $wpdb->update("$table_name",[

                'emp_id' =>sanitize_text_field($_REQUEST['emp_id']),

                'emp_name' =>sanitize_text_field($_REQUEST['emp_name']),

                'emp_email' =>sanitize_email($_REQUEST['emp_email']),

                'emp_dept' =>sanitize_text_field($_REQUEST['emp_dept'])],

                ['id' => $id]);

            if($update){

                $msg = "Data Updated <a href='".get_page_link(get_the_ID())."'>Add Employee</a>";

            }

        }

        $employee = $wpdb->get_row($wpdb->prepare("select * from $table_name where id = %d", $id), ARRAY_A);


        $emp_id = $employee['emp_id'];

        $emp_name = $employee['emp_name'];

        $emp_email = $employee['emp_email'];

        $emp_dept = $employee['emp_dept'];

    }

    if(@$_REQUEST['action'] == 'delete-emp' && @$_REQUEST['id']){

        $id = @$_REQUEST['id'];

        if($id){

            $row_exits = $wpdb->get_row($wpdb->prepare("select * from $table_name where id = %d",$id),ARRAY_A);

            if(count($row_exits)> 0){

                $wpdb->delete("$table_name", array('id'=>$id));

            }

        }

        ?>

            <script>

                location.href="<?php echo get_the_permalink(); ?>";

            </script>

        <?php

    }

    ?>

    <div class="form_container">


    <h4><?php echo @$msg; ?></h4>

    <form method="post">


        <p>

            <label>EMP ID</label>

            <input type="text" name="emp_id" value="<?php echo @$emp_id; ?>" placeholder="Enter ID" required>


        </p>


        <p>

            <label>Name</label>

            <input type="text" name="emp_name"  value="<?php echo @$emp_name; ?>" placeholder="Enter Name" required>


        </p>

        <p>

            <label>Email</label>

            <input type="email" name="emp_email" value="<?php echo @$emp_email; ?>" placeholder="Enter Email" required>

        </p>

        <p>

            <label>Department</label>

            <input type="text" name="emp_dept" value="<?php echo @$emp_dept; ?>" placeholder="Enter Department" required>

        </p>


        <p>

            <button type="submit" name="action" value="<?php echo (@$_REQUEST['action'] == 'update-emp')?'update-emp':'submit'; ?>"><?php echo (@$_REQUEST['action'] == 'update-emp')?'Update':'Submit'; ?></button>

        </p>

    </form>


    </div>

<?php


    $employee_list = $wpdb->get_results("SELECT * FROM $table_name", ARRAY_A);

    $i = 1;

    if($employee_list > 0 ){ ?>


        <div style="margin-top: 40px">

            <table border="1" cellpadding="10" style="font-size:14px;">

                <tr>

                <th>S. No.</th>

                <th>EMP ID</th>

                <th>Name</th>

                <th>Email</th>

                <th>Dept.</th>

                <th>Action</th>

                </tr>

                <?php foreach ($employee_list as $index =>  $employee):


                    ?>

                    <tr>

                        <td><?php echo $i++; ?></td>

                        <td><?php echo $employee['emp_id'];  ?></td>

                        <td><?php echo $employee['emp_name']; ?></td>

                        <td><?php echo $employee['emp_email'];; ?></td>

                        <td><?php echo $employee['emp_dept'];; ?></td>

                        <td>

                            <a href="?action=update-emp&id=<?php echo $employee['id']; ?>">Update</a>

                            <a href="?action=delete-emp&id=<?php echo $employee['id']; ?>" onclick="return confirm('Are you sure to remove this record?')">Delete</a>

                        </td>

                    </tr>

                <?php endforeach; ?>

            </table>

        </div>

    <?php }

}


Wednesday, November 16, 2022

wordpress crud plugin admin side

Today I explain simple crud operation in admin side by plugin.

Folder name : crud

File name : crud.php



<?php

/*

Plugin Name: CRUD Operations

Plugin URI: #

Description: A simple plugin that allows you to perform Create (INSERT), Read (SELECT), Update and Delete operations.

Version: 1.0.0

Author: Chirag

Author URI: #

License: GPL2

*/

register_activation_hook( __FILE__, 'crudOperationsTable');

function crudOperationsTable() {

  global $wpdb;

  $charset_collate = $wpdb->get_charset_collate();

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

  $sql = "CREATE TABLE `$table_name` (

  `user_id` int(11) NOT NULL AUTO_INCREMENT,

  `name` varchar(220) DEFAULT NULL,

  `email` varchar(220) DEFAULT NULL,

  PRIMARY KEY(user_id)

  ) ENGINE=MyISAM DEFAULT CHARSET=latin1;

  ";

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

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

    dbDelta($sql);

  }

}

add_action('admin_menu', 'addAdminPageContent');

function addAdminPageContent() {

  add_menu_page('CRUD', 'CRUD', 'manage_options' ,__FILE__, 'crudAdminPage', 'dashicons-wordpress');

}

function crudAdminPage() {

  global $wpdb;

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

  if (isset($_POST['newsubmit'])) {

    $name = $_POST['newname'];

    $email = $_POST['newemail'];

    if (!empty($name) && !empty($email)) {

      $wpdb->query("INSERT INTO $table_name(name,email) VALUES('$name','$email')");

      echo "<script>location.replace('admin.php?page=crud%2Fcrud.php');</script>";

    }

    

  }

  if (isset($_POST['uptsubmit'])) {

    $id = $_POST['uptid'];

    $name = $_POST['uptname'];

    $email = $_POST['uptemail'];

    if (!empty($name) && !empty($email)) {

      $wpdb->query("UPDATE $table_name SET name='$name',email='$email' WHERE user_id='$id'");

      echo "<script>location.replace('admin.php?page=crud%2Fcrud.php');</script>"; 

    }

  }

  if (isset($_GET['del'])) {

    $del_id = $_GET['del'];

    $wpdb->query("DELETE FROM $table_name WHERE user_id='$del_id'");

    echo "<script>location.replace('admin.php?page=crud%2Fcrud.php');</script>";

  }

  ?>

  <div class="wrap">

    <h2>CRUD Operations</h2>

    <table class="wp-list-table widefat striped">

      <thead>

        <tr>

          <th width="25%">User ID</th>

          <th width="25%">Name</th>

          <th width="25%">Email Address</th>

          <th width="25%">Actions</th>

        </tr>

      </thead>

      <tbody>

        <form action="" method="post">

          <tr>

            <td><input type="text" value="AUTO_GENERATED" disabled></td>

            <td><input type="text" id="newname" name="newname"></td>

            <td><input type="text" id="newemail" name="newemail"></td>

            <td><button id="newsubmit" name="newsubmit" type="submit">INSERT</button></td>

          </tr>

        </form>

        <?php

          $result = $wpdb->get_results("SELECT * FROM $table_name");

          foreach ($result as $print) {

            echo "

              <tr>

                <td width='25%'>$print->user_id</td>

                <td width='25%'>$print->name</td>

                <td width='25%'>$print->email</td>

                <td width='25%'><a href='admin.php?page=crud%2Fcrud.php&upt=$print->user_id'><button type='button'>UPDATE</button></a> <a href='admin.php?page=crud%2Fcrud.php&del=$print->user_id'><button type='button'>DELETE</button></a></td>

              </tr>

            ";

          }

        ?>

      </tbody>  

    </table>

    <br>

    <br>

    <?php

      if (isset($_GET['upt'])) {

        $upt_id = $_GET['upt'];

        $result = $wpdb->get_results("SELECT * FROM $table_name WHERE user_id='$upt_id'");

        foreach($result as $print) {

          $name = $print->name;

          $email = $print->email;

        }

        echo "

        <table class='wp-list-table widefat striped'>

          <thead>

            <tr>

              <th width='25%'>User ID</th>

              <th width='25%'>Name</th>

              <th width='25%'>Email Address</th>

              <th width='25%'>Actions</th>

            </tr>

          </thead>

          <tbody>

            <form action='' method='post'>

              <tr>

                <td width='25%'>$print->user_id <input type='hidden' id='uptid' name='uptid' value='$print->user_id'></td>

                <td width='25%'><input type='text' id='uptname' name='uptname' value='$print->name'></td>

                <td width='25%'><input type='text' id='uptemail' name='uptemail' value='$print->email'></td>

                <td width='25%'><button id='uptsubmit' name='uptsubmit' type='submit'>UPDATE</button> <a href='admin.php?page=crud%2Fcrud.php'><button type='button'>CANCEL</button></a></td>

              </tr>

            </form>

          </tbody>

        </table>";

      }

    ?>

  </div>

  <?php

}