CRUD ( Create Read Update Delete) data dengan php mysql jquery)

Posted on Updated on


1
Siapkan table  tb_mahasiswa
  1. CREATE TABLE `tb_mahasiswa` (
      `nim` varchar(8) NOT NULL,
      `nama` varchar(30) NOT NULL,
      `tempat_lahir` varchar(30) NOT NULL,
      `alamat` varchar(200) DEFAULT NULL,
      PRIMARY KEY (`nim`)
    ) ENGINE=MyISAM DEFAULT CHARSET=latin1

Buat halaman index.php
Halaman ini nanti akan di gunakan sebagai frame dari data-data yang di panggil
  1. <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;
    <head>
    <meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
    <title>ajax CRUD</title>
    $(function() {
                //request menu
                $(“[id^=mn]”).click(function(){
                            $(‘#resulmanager’).html(‘loading…’);
                // get tab id and tab url
                            tabId = $(this).attr(“id”);
                            tabUrl = $(“#”+tabId).attr(“href”);
                            $(‘#resulmanager’).load(tabUrl);
                            return false;
                });
                //hapus data
                $(‘.delete’).live(“click”,function() {
                var nim = $(this).attr(“nim”);
                if(confirm(“yakin data ini mau di delete??”))
                {
                            $.ajax({
                                                    type: “POST”,
                                                    url: “./proses.php?mode=delete”,
                                                    data:”nim=”+nim,
                                                    cache: false,
                                                    success: function(html){
                                                                $(“#list_”+nim).slideUp(‘slow’, function() {$(this).remove();});
                                        }
                            });
                            return false;
                            }
                });
    });
    <style>
    body{
                font-family:Tahoma, Geneva, sans-serif;
                font-size:11px;
    }
    .grid{
    }
    .grid th{
                padding:5px;
                border-bottom:1px solid #CCC;
    }
    .grid td{
                padding:5px;
                border-bottom:1px solid #CCC;
    }
    .kotak{
                border:1px solid #666;
                margin:auto;
                width:500px;
    }
    </style>
    </head>
    <!–
    $(“#resulmanager”).load(“./mahasiswa.php?aksi=list”); supaya pas panggil halaman index pertama akan di tampilkan list data
    jika akan menampilkan form input
    $(“#resulmanager”).load(“./mahasiswa.php?aksi=forminput”);  maka index pertama akan di tampilkan input data
    –>
    <body onload=’$(“#resulmanager”).load(“./mahasiswa.php?aksi=list”);’>
    <!– semua data yang di request aakn di tampilkan di sini –>
       
    Loading..
    </div>
    </body>
    </html>
Buat halaman mahasiswa.php
  1. $(function() {
    //request input data
    $(“form#frm_input”).submit(function(){
                $(“#result”).show();
                var nim = $(“#nim”).attr(‘value’);
                var nama = $(“#nama”).attr(‘value’);
                var tmplahir = $(“#tmplahir”).attr(‘value’);
                var alamat = $(“#alamat”).attr(‘value’);
                //periksa data field infutnya di isi?
                //silahkan validasi sesuai keinginan anda
                if(nim==”){
                            alert(‘nim harus di isi’);
                            return false;
                }
                $.ajax({
                                        type: “POST”,
                                        url: “./proses.php?mode=add”,
                                        data:”nim=”+nim+’&nama=’+nama+’&tmplahir=’+tmplahir+’&alamat=’+alamat,
                                        success: function(data){
                                                    $(“#result”).html(data);
                                        }
                });
                return false;
                });
    //request edit
    $(“form#frm_edit”).submit(function(){
                $(“#result”).show();
                var nim = $(“#nim”).attr(‘value’);
                var nama = $(“#nama”).attr(‘value’);
                var tmplahir = $(“#tmplahir”).attr(‘value’);
                var alamat = $(“#alamat”).attr(‘value’);
                //periksa data field infutnya di isi?
                //silahkan validasi sesuai keinginan anda
                $.ajax({
                                        type: “POST”,
                                        url: “./proses.php?mode=edit”,
                                        data:”nim=”+nim+’&nama=’+nama+’&tmplahir=’+tmplahir+’&alamat=’+alamat,
                                        success: function(data){
                                                    $(“#result”).html(data);
                                        }
                });
                return false;
                });
    });
    <?php
    mysql_connect(‘localhost’,’root’,”);
    mysql_select_db(‘test’);
    //jika halaman yang di request  list data mahasiswa
    if(isset($_GET[‘aksi’]) && $_GET[‘aksi’] == ‘list’){
                $query=mysql_query(“SELECT * FROM `tb_mahasiswa`”);
                echo “<table cellpading=’1′ cellspacing=’1′ width=’100%’ border=’0′ class=’grid’>”;
                echo “<tr><th>No</th><th>Nim</th><th>Nama</th><th>Opsi</th></tr>”;
                //jika tidak ada record
                if($jum=mysql_num_rows($query) == 0){
                            echo “<tr><td colspan=’4′>tidak ada data</td></tr>”;
                }
                $no=0;
                while($row=mysql_fetch_object($query)){
                            $no++;
                            //pemberian id=’list_{$row->nim}’ pada tag tr nanti akan di gunakan jika data di delete maka baris record tersebut akan di delete
                            echo “<tr id=’list_{$row->nim}’>”;
                            echo “<td> {$no} </td>”;
                            echo “<td> {$row->nim} </td>”;
                            echo “<td> {$row->nama} </td>”;
                            //pemberian atribut class dan nim sangat penting karena nanti untuk menghapus data parameter tersebut yang akan di jadikan acuan
                            echo “<td> <a href=’#’ class=’delete’ nim='{$row->nim}’>delete</a> – “;
                            echo “<a href=’#’ onclick=’$(\”#resulmanager\”).load(\”./mahasiswa.php?aksi=formedit&nim={$row->nim}\”);’> edit </td>”;
                            echo “</tr>”;
                }
                echo “</table>”;
                echo “

    “;

    exit();
    }
    //jika halaman yang di request  input data mahasiswa
    if(isset($_GET[‘aksi’]) && $_GET[‘aksi’] == ‘forminput’){
                echo “
     

    “; // untuk nanti data calllbach hasil request akan di tampilkan disini

                echo “<form id=’frm_input’>”;
                echo “<table cellpading=’1′ cellspacing=’1′ width=’100%’ border=’0′>”;
                //pemberian atribut id sangat penting.. karena nilai yang di ambil dari fild tersebut nanti berdasarkan id tersebut
                echo “<tr><td width=’30%’>Nim</td><td><input type=’text’ name=’nim’ id=’nim’></td></tr>”;
                echo “<tr><td>Nama</td><td><input type=’text’ name=’nama’ id=’nama’></td></tr>”;
                echo “<tr><td>Tempat lahir</td><td><input type=’text’ name=’tmplahir’ id=’tmplahir’></td></tr>”;
                echo “<tr><td>Alamat</td><td><input type=’text’ name=’alamat’ id=’alamat’></td></tr>”;
                echo “<tr><td>&nbsp;</td><td><input type=’submit’ value=’kirim’></td></tr>”;
                echo “</table>”;
                echo “</form>”;
                exit();
    }
    //jika halaman yang di request  edit data mahasiswa
    if(isset($_GET[‘aksi’]) && $_GET[‘aksi’] == ‘formedit’){
                //ambil data mahasiswa
                $query=mysql_fetch_object(mysql_query(“SELECT * FROM `tb_mahasiswa` WHERE `nim` = ‘{$_GET[‘nim’]}'”));
                echo “
     

    “; // untuk nanti data calllbach hasil request akan di tampilkan disini

                echo “<form id=’frm_edit’>”;
                echo “<table cellpading=’1′ cellspacing=’1′ width=’100%’ border=’0′>”;
                //pemberian atribut id sangat penting.. karena nilai yang di ambil dari fild tersebut nanti berdasarkan id tersebut
                echo “<tr><td width=’30%’>Nim</td><td><input type=’text’ disabled=’disabled’ value='{$query->nim}’></td></tr>”;
                echo “<tr><td>Nama</td><td><input type=’text’ name=’nama’ id=’nama’ value='{$query->nama}’></td></tr>”;
                echo “<tr><td>Tempat lahir</td><td><input type=’text’ name=’tmplahir’ id=’tmplahir’ value='{$query->tempat_lahir}’></td></tr>”;
                echo “<tr><td>Alamat</td><td><input type=’text’ name=’alamat’ id=’alamat’ value='{$query->alamat}’></td></tr>”;
                //paramaeter kunci
                echo “<input type=’hidden’ name=’nim’ id=’nim’ value='{$query->nim}’>”;
                echo “<tr><td>&nbsp;</td><td><input type=’submit’ value=’kirim’></td></tr>”;
                echo “</table>”;
                echo “</form>”;
                exit();
    }
    ?>
 
Buat halaman proses.php
  1. <?php
    mysql_connect(‘localhost’,’root’,”);
    mysql_select_db(‘test’);
    //tambah data
    if(isset($_GET[‘mode’]) && $_GET[‘mode’] == ‘add’){
                //periksa apakah nim sudah di gunakan
                $query=mysql_query(“SELECT * FROM `tb_mahasiswa` WHERE `nim` = ‘{$_POST[‘nim’]}'”);
                if($jum=mysql_num_rows($query) > 0){
                            $error=true;
                            echo “nim sudah di gunakan”;
                            exit();
                }
                if(!$error){
                            $query=mysql_query(“INSERT INTO `tb_mahasiswa` (
                                                                               `nim`,
                                                                               `nama`,
                                                                               `tempat_lahir`,
                                                                               `alamat`
                                                                               )VALUES(
                                                                               ‘{$_POST[‘nim’]}’,
                                                                               ‘{$_POST[‘nama’]}’,
                                                                               ‘{$_POST[‘tmplahir’]}’,
                                                                               ‘{$_POST[‘alamat’]}’)
                                                                               “);
                            if($query){
                                        echo “data sudah di masukan”;
                            }
                }
    exit();
    }
    //edit data
    if(isset($_GET[‘mode’]) && $_GET[‘mode’] == ‘edit’){
                            $query=mysql_query(“UPDATE `tb_mahasiswa` SET
                                                                               `nama` = ‘{$_POST[‘nama’]}’,
                                                                               `tempat_lahir` =  ‘{$_POST[‘tmplahir’]}’,
                                                                               `alamat`        =  ‘{$_POST[‘alamat’]}’
                                                                              WHERE `nim` = ‘{$_POST[‘nim’]}'”);
                            if($query){
                                        echo “data sudah di edit”;
                            }
    exit();
    }
    //delete data
    if(isset($_GET[‘mode’]) && $_GET[‘mode’] == ‘delete’){
                $nim=$_POST[‘nim’];
                $query=mysql_query(“DELETE FROM `tb_mahasiswa` WHERE `nim` = ‘{$nim}’ “);
    }
    ?>

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s