CodeIgniter CRUD Basics (CCRUDB)

This is a scrap code from studying DBMS in semester 3, or I can also say this is a historical legacy of learning in college at that time. Where I was given an assignment by the lecturer to create a simple Create, Read, Update, Delete system abbreviated as CRUD, using the CodeIgniter framework.

Step 1

please run wampserver or localserver similar, then enter phpmyadmin or you can also use the terminal if you already feel PRO. Please create a database with an academic name.

Step 2

If you are using phpmyadmin GUI, then you can save the code below as a *sql file which you can later import in phpmyadmin of course in the academic database, or you can also run it in phpmysql with SQL mode by opening the SQL tabulation.

-- phpMyAdmin SQL Dump
-- version 4.6.4
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: May 25, 2019 at 10:52 PM
-- Server version: 5.7.14
-- PHP Version: 5.6.25

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `akademik`
--

-- --------------------------------------------------------

--
-- Table structure for table `dosen`
--

CREATE TABLE `dosen` (
  `iddosen` int(11) NOT NULL,
  `nama` varchar(50) NOT NULL,
  `alamat` varchar(100) NOT NULL,
  `notelp` varchar(15) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- --------------------------------------------------------

--
-- Table structure for table `kuliah`
--

CREATE TABLE `kuliah` (
  `idkuliah` int(11) NOT NULL,
  `iddosen` int(11) NOT NULL,
  `idmatakuliah` int(11) NOT NULL,
  `nim` varchar(10) NOT NULL,
  `nilai` enum('A','B','C','D','E') DEFAULT NULL,
  `thajaran` varchar(5) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- --------------------------------------------------------

--
-- Table structure for table `mahasiswa`
--

CREATE TABLE `mahasiswa` (
  `nim` int(10) NOT NULL,
  `nama` varchar(50) NOT NULL,
  `alamat` varchar(100) NOT NULL,
  `jnskel` enum('lAKI-LAKI','Perempuan') DEFAULT NULL,
  `prodi` varchar(20) NOT NULL,
  `notelp` varchar(15) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `mahasiswa`
--

INSERT INTO `mahasiswa` (`nim`, `nama`, `alamat`, `jnskel`, `prodi`, `notelp`) VALUES
(101010, 'bundet', 'bundet.com', 'lAKI-LAKI', 'ti', '*888#'),
(1111111, 'rrr', 'yyy', 'lAKI-LAKI', 'uu', '0000'),
(12131294, 'wawan', 'harjo kasihan bantul', 'Perempuan', 'DBMS', '08566');

-- --------------------------------------------------------

--
-- Table structure for table `matakuliah`
--

CREATE TABLE `matakuliah` (
  `idmatakuliah` int(11) NOT NULL,
  `nama` varchar(50) NOT NULL,
  `sks` tinyint(1) NOT NULL,
  `semester` enum('Gasal','Genap') DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `dosen`
--
ALTER TABLE `dosen`
  ADD PRIMARY KEY (`iddosen`);

--
-- Indexes for table `kuliah`
--
ALTER TABLE `kuliah`
  ADD PRIMARY KEY (`idkuliah`);

--
-- Indexes for table `mahasiswa`
--
ALTER TABLE `mahasiswa`
  ADD PRIMARY KEY (`nim`);

--
-- Indexes for table `matakuliah`
--
ALTER TABLE `matakuliah`
  ADD PRIMARY KEY (`idmatakuliah`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `dosen`
--
ALTER TABLE `dosen`
  MODIFY `iddosen` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `kuliah`
--
ALTER TABLE `kuliah`
  MODIFY `idkuliah` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `mahasiswa`
--
ALTER TABLE `mahasiswa`
  MODIFY `nim` int(10) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=12131295;
--
-- AUTO_INCREMENT for table `matakuliah`
--
ALTER TABLE `matakuliah`
  MODIFY `idmatakuliah` int(11) NOT NULL AUTO_INCREMENT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

Step 3

Download the CodeIgniter framework, and extract it to the www folder (if wampserver) or to htdoc (if xampp), put it in the folder you have prepared.

Step 4

Database configuration, go to application/config/database.php, adjust it to the database that was created earlier.

$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '';
$db['default']['database'] = 'akademik';
$db['default']['dbdriver'] = 'mysql';
$db['default']['dbprefix'] = '';
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = TRUE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = '';
$db['default']['char_set'] = 'utf8';
$db['default']['dbcollat'] = 'utf8_general_ci';
$db['default']['swap_pre'] = '';
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;

Step 5

base url configuration, go to application/config/config.php, adjust it to the folder name you created in www or htdoc.

/*
|--------------------------------------------------------------------------
| Base Site URL
|--------------------------------------------------------------------------
|
| URL to your CodeIgniter root. Typically this will be your base URL,
| WITH a trailing slash:
|
|   http://example.com/
|
| If this is not set then CodeIgniter will guess the protocol, domain and
| path to your installation.
|
*/
$config['base_url'] = 'http://localhost/12131294_WawanChahyoNugroho/';

Step 6

default controller configuration, go to application/config/routes.php, because later we will create a main controller named Main.php, so define it here.

| -------------------------------------------------------------------------
| RESERVED ROUTES
| -------------------------------------------------------------------------
|
| There area two reserved routes:
|
|   $route['default_controller'] = 'welcome';
|
| This route indicates which controller class should be loaded if the
| URI contains no data. In the above example, the "welcome" class
| would be loaded.
|
|   $route['404_override'] = 'errors/page_missing';
|
| This route will tell the Router what URI segments to use if those provided
| in the URL cannot be matched to a valid route.
|
*/

$route['default_controller'] = "main";

Step 7

library and helper configuration, go to application/config/autoload.php, please set these parts.

/*
| -------------------------------------------------------------------
|  Auto-load Packges
| -------------------------------------------------------------------
| Prototype:
|
|  $autoload['packages'] = array(APPPATH.'third_party', '/usr/local/shared');
|
*/
$autoload['packages'] = array('database');

This

/*
| -------------------------------------------------------------------
|  Auto-load Libraries
| -------------------------------------------------------------------
| These are the classes located in the system/libraries folder
| or in your application/libraries folder.
|
| Prototype:
|
|   $autoload['libraries'] = array('database', 'session', 'xmlrpc');
*/
$autoload['libraries'] = array('database');

and this

/*
| -------------------------------------------------------------------
|  Auto-load Helper Files
| -------------------------------------------------------------------
| Prototype:
|
|   $autoload['helper'] = array('url', 'file');
*/
$autoload['helper'] = array('url');

Step 8

create a controller file in application/controllers named Main.php and fill it with the following code.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Main extends CI_Controller {
    function __construct(){
            parent::__construct();
            $this->load->model('mahasiswa_m');
        }

    public function index()
    {
        $data['mhs'] = $this->mahasiswa_m->get_all();
        $this->load->view('tmahasiswa_v', $data);
    }
    public function input(){
        $this->load->view('imahasiswa_v');
    }
    public function simpan(){
        $this->mahasiswa_m->insert();
        redirect('main');
    }
    public function hapus(){
        $nim = $this->uri->segment(3);
        $this->mahasiswa_m->delete($nim);
        redirect('main');
    }
    public function edit(){
        $nim = $this->uri->segment(3);
        $data['mhs'] = $this->mahasiswa_m->get_one($nim);
        $this->load->view('emahasiswa_v', $data);
    }
}

Step 9

create a model file in application/models to communicate with the database, name it Mahasiswa_m.php

<?php
    class Mahasiswa_m extends CI_Model{
        function __construct(){
            parent::__construct();
        }

        function get_all(){
            $sql = 'SELECT * FROM mahasiswa';
            return $this->db->query($sql);
        }

        function insert(){
        $data = array(
            'nim' => $this->input->post('nim'),
            'nama' => $this->input->post('nama'),
            'alamat' => $this->input->post('alamat'),
            'jnskel' => $this->input->post('jnskel'),
            'prodi' => $this->input->post('prodi'),
            'notelp' => $this->input->post('notelp'),
            );

        if($this->input->post('nimcek')){
            $this->db->where('nim', $this->input->post('nim'));
            $this->db->update('mahasiswa', $data);
        }
        else{
            $this->db->insert('mahasiswa', $data);
            }
        }

function get_one($nim){
        $sql = 'SELECT * FROM mahasiswa WHERE nim = '.$nim;
        $hasil = $this->db->query($sql);
        if($hasil->num_rows()){
            return $hasil->row();
            }else{
                return false;
            }
        }

        function delete($nim){
        if($nim){
            $sql = 'DELETE FROM mahasiswa WHERE nim = '.$nim;
            $this->db->query($sql);
            }
        }
    }
?>

Step 10

create some view files in application/views for display in the browser.

emahasiswa_v.php

<form method="post" action="<?php echo base_url()?>main/simpan">
<input type="hidden" name="nimcek" value="<?php echo $mhs->nim?>" />
<table>
    <tr>
        <td>NIM</td>
        <td><input type="text" name="nim" value="<?php echo $mhs->nim?>" size="10" /></td>
        </tr>
    <tr>
        <td>Nama</td>
        <td><input type="text" name="nama" value="<?php echo $mhs->nama?>" size="30" /></td>
        </tr>
    <tr>
        <td>Alamat</td>
        <td><input type="text" name="alamat" value="<?php echo $mhs->alamat?>" size="40" /></td>
        </tr>
    <tr>
        <td>Jenis Kelamin</td>
        <td>
        <input type="radio" name="jnskel" value="Laki-laki" /> Laki-laki
        <input type="radio" name="jnskel" value="Perempuan" /> Perempuan
        </td>
        </tr>
    <tr>
        <td>Prodi</td>
        <td><input type="text" name="prodi" value="<?php echo $mhs->prodi?>" size="20" /><td>
        </tr>
    <tr>
        <td>No.Telp</td>
        <td><input type="text" name="notelp" value="<?php echo $mhs->notelp?>" size="12" /><td>
        </tr>
    <td>&nbsp;</td>
    <td><input type="submit" value="Simpan" /></td>

</table>
</form>

student_v.php

<form method="post" action="<?php echo base_url()?>main/simpan">
<table>
    <tr>
        <td>NIM</td>
        <td><input type="text" name="nim" size="10" /></td>
        </tr>
    <tr>
        <td>Nama</td>
        <td><input type="text" name="nama" size="30" /></td>
        </tr>
    <tr>
        <td>Alamat</td>
        <td><input type="text" name="alamat" size="40" /></td>
        </tr>
    <tr>
        <td>Jenis Kelamin</td>
        <td>
        <input type="radio" name="jnskel" value="Laki-laki" /> Laki-laki
        <input type="radio" name="jnskel" value="Perempuan" /> Perempuan
        </td>
        </tr>
    <tr>
        <td>Prodi</td>
        <td><input type="text" name="prodi" size="20" /><td>
        </tr>
    <tr>
        <td>No.Telp</td>
        <td><input type="text" name="notelp" size="12" /><td>
        </tr>
    <td>&nbsp;</td>
    <td><input type="submit" value="Simpan" /></td>

</table>
</form>

tmahasiswa_v.php

<table border="1">
<tr>
        <th>No</th>
        <th>NIM</th>
        <th>NAMA</th>
        <th>ALAMAT</th>
        <th>JENIS KELAMIN</th>
        <th>PRODI</th>
        <th>NO.TELP</th>
        <th>KELOLA</th>
</tr>
    <?php $no=1; foreach($mhs->result() as $m) {?>
    <tr>
        <td><?php echo $no++?></td>
        <td><?php echo $m->nim?></td>
        <td><?php echo $m->nama?></td>
        <td><?php echo $m->alamat?></td>
        <td><?php echo $m->jnskel?></td>
        <td><?php echo $m->prodi?></td>
        <td><?php echo $m->notelp?></td>
        <td>
        <?php echo anchor('main/edit/'.$m->nim, 'Edit')?>
        <?php echo anchor('main/hapus/'.$m->nim, 'Hapus')?>
        </td>
    </tr>
    <?php } ?>
</table>
<a href="http://localhost/12131294_WawanChahyoNugroho/main/input">INPUT<a/>

Step 11

Done!!, run the application in your favorite browser.
Happy Coding!

Creating CodeIgniter Delete Confirmation

Hi guys, while I'm in a good mood, I want to share again about one of my experiences while developing this site.

Okay, so the story goes like this, let's say I have 1 admin page that contains a list of articles. Previously, I never gave any confirmation alert when pressing the delete button. Well, one day a problem arose, namely because of an error in the mouse, suddenly an important article that I had was deleted just like that. From there I felt confused and regretful, then the positive energy from that regret made me intend to create the delete confirm alert.

On the journey, of course, it is not as smooth as Blackpink's thighs, well, it is understandable that the twists and turns of learning for newbies have become a daily occurrence.

The following pseudocode may give you a little idea of ​​what I want to achieve in developing this site into the next version.

Javascript code.

function ConfirmDialog() {
  var x=confirm("Are you sure to delete record?")
  if (x) {
    return true;
  } else {
    return false;
  }
}

PHP of view.

<?php
  echo anchor('user/deleteuser/'.$row->id, 'Delete', array('class'=>'delete', 'onclick'=>"return ConfirmDialog();"));
?>

Simulation

<!DOCTYPE html>
<html>
<body>

<p>Click the button to display a confirm box.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
  var txt;
  var r = confirm("Press a button!");
  if (r == true) {
    txt = "You pressed OK!";
  } else {
    txt = "You pressed Cancel!";
  }
  document.getElementById("demo").innerHTML = txt;
}
</script>

</body>
</html>

Solution

Delete button hyperlink.

<a href="javascript:void(0);" onclick="delete(<?php echo $row->id;?>);">Delete</a>

Set up the delete() javascript function in such a way.

<script type="text/javascript">
    var url="<?php echo base_url();?>";
    function delete(id){
       var r=confirm("Do you want to delete this?")
        if (r==true)
          window.location = url+"user/deleteuser/"+id;
        else
          return false;
        }
</script>

If you have difficulty casting the id value from php code to javascript code, please just ask via the comments column.


Post a Comment

Previous Next

نموذج الاتصال