Kategori
PHP

Tutorial Searching Data with PHP and Mysql

Case Study : Create script for searching data in the database
Requirements : Webserver Packages, already installed.

Searching, is a facility that is almost always present in every application, whether web based or desktop applications. Each web page / blog will also equipped with this facility. The following tutorial will provide the basic concept of searching, by doing a search on terstruktu data (database).

Ok, just straight practice.

Step 1 : Prepare the Database

  1. Create database named db_tutorial
  2. Create table named tb_student, the structure is as shown below,
  3. Insert some sample data, just like in this picture.
  4. Done with the database!

Step 2 : Prepare the Work Folder

  1. Create a folder with the name searching in your document root
  2. Save all this file in this tutorial in this folder.

Step 3 : Create script to connect to DB

  1. Type the following script,
    [sourcecode language=”php”]
    <?php
    $host = "localhost";
    $user = "root";
    $pass = "";
    $dbName = "db_tutorial";
    mysql_connect($host, $user, $pass);
    mysql_select_db($dbName)
    or die ("Connect Failed !! : ".mysql_error());
    ?>
    [/sourcecode]
  2. Save with the name connect.php

  3. Explanation: The script will be used for linking us with a database application db_tutorial. Customize your username and password from the settings of your mysql.

Step 4 : Create a Searching Form

  1. Type the following script,
    [sourcecode language=”php”]
    <html>
    <head>
    <title> Halaman Pencarian </title>
    </head>
    <body>
    <form name="formcari" method="post" action="search_exe.php">
    <table width="330" border="0" align="center" cellpadding="0">
    <tr bgcolor="orange">
    <td height="25" colspan="3">
    <strong> Student Searching ! </strong>
    </td>
    </tr>
    <tr> <td> Name </td>
    <td> <input type="text" name="name"> </td>
    </tr>
    <td></td>
    <td> <input type="SUBMIT" name="SUBMIT" id="SUBMIT" value="search" > </td>
    </table>
    </form>
    </body>
    </html>
    [/sourcecode]
  2. Save with the name formsearching.php
  3. Explanation: The script above is a normal HTML script that will display the form. See the part,
    action="search_exe.php", bagian ini dimaksudkan bahwa form akan diproses oleh script search_exe.php

Step 5 : Create a processing script and displays the results of searching

  1. Type the following script,
    [sourcecode language=”php”]
    <?php
    include "connect.php";
    $name= $_POST[‘name’]; //get the nama value from form
    $q = "SELECT * from tb_student where name like ‘%$name%’ "; //query to get the search result
    $result = mysql_query($q); //execute the query $q
    echo "<center>";
    echo "<h2> Hasil Searching </h2>";
    echo "<table border=’1′ cellpadding=’5′ cellspacing=’8′>";
    echo "
    <tr bgcolor=’orange’>
    <td>No</td>
    <td>Nama Mahasiswa</td>
    <td>Alamat</td>
    </tr>";
    while ($data = mysql_fetch_array($result)) { //fetch the result from query into an array
    echo "
    <tr>
    <td>".$data[‘no’]."</td>
    <td>".$data[‘name’]."</td>
    <td>".$data[‘address’]."</td>
    </tr>";
    }
    echo "</table>";
    ?>
    [/sourcecode]
  2. Save with the name search_exe.php
  3. The explanation can be found at comment script

Step 6 : Testing Code

  1. Go to http://localhost/searching/formsearching.php. You can see the form like the picture below,
  2. Enter the name of the field name (eg name that has diinsert to the DB, namely june )
  3. Click the search button and you will see results,

Be creative with PHP πŸ˜€ Happy Coding..

Kategori
PHP

Tutorial Searching / Pencarian Data dengan PHP dan Mysql

Studi Kasus : Membuat script untuk pencarian data dalam database
Kebutuhan : Webserver Packages, already installed.

Searching, merupakan fasilitas yang hampir selalu ada dalam setiap aplikasi, baik aplikasi berbasis web ataupun desktop. Setiap halaman web/ blog juga akan ditemukan fasilitas ini. Tutorial berikut akan memberikan konsep dasar dari searching, dengan melakukan pencarian pada data terstruktu (database).

Ok, langsung praktik saja.

Step 1 : Persiapkan Database

  1. Buat database dengan nama db_tutorial
  2. Siapkan tabel dengan nama tb_student, dengan struktur tabel seperti gambar dibawah ini.
  3. Insert-kan beberapa sample data, misal seperti gambar dibawah,
  4. Done with the database!

Step 2 : Persiapkan Folder Kerja

  1. Buat folder dengan nama searching dalam document root anda
  2. Simpan semua file dalam praktikum ini dalam folder tersebut.

Step 3 : Membuat script koneksi ke DB

  1. Ketikkan script berikut,
    [sourcecode language=”php”]
    <?php
    $host = "localhost";
    $user = "root";
    $pass = "";
    $dbName = "db_tutorial";
    mysql_connect($host, $user, $pass);
    mysql_select_db($dbName)
    or die ("Connect Failed !! : ".mysql_error());
    ?>
    [/sourcecode]
  2. simpan dengan nama connect.php
  3. Penjelasan : Script ini akan digunakan untuk menghubungan aplikasi kita dengan database db_tutorial. Sesuaikan username dan password dengan setting-an mysql anda.

Step 4 : Membuat form pencarian

  1. Ketikkan script berikut,
    [sourcecode language=”php”]
    <html>
    <head>
    <title> Halaman Pencarian </title>
    </head>
    <body>
    <form name="formcari" method="post" action="search_exe.php">
    <table width="330" border="0" align="center" cellpadding="0">
    <tr bgcolor="orange">
    <td height="25" colspan="3">
    <strong> Student Searching ! </strong>
    </td>
    </tr>
    <tr> <td> Name </td>
    <td> <input type="text" name="name"> </td>
    </tr>
    <td></td>
    <td> <input type="SUBMIT" name="SUBMIT" id="SUBMIT" value="search" > </td>
    </table>
    </form>
    </body>
    </html>
    [/sourcecode]
  2. simpan dengan nama formsearching.php
  3. Penjelasan : script diatas adalah HTML script biasa yang akan menampilkan form. Perhatian bagian action="search_exe.php", bagian ini dimaksudkan bahwa form akan diproses oleh script search_exe.php

Step 5 : Membuat script pemrosesan dan menampilkan hasil searching

  1. Ketikkan script berikut,
    [sourcecode language=”php”]
    <?php
    include "connect.php";
    $name= $_POST[‘name’]; //get the nama value from form
    $q = "SELECT * from tb_student where name like ‘%$name%’ "; //query to get the search result
    $result = mysql_query($q); //execute the query $q
    echo "<center>";
    echo "<h2> Hasil Searching </h2>";
    echo "<table border=’1′ cellpadding=’5′ cellspacing=’8′>";
    echo "
    <tr bgcolor=’orange’>
    <td>No</td>
    <td>Nama Mahasiswa</td>
    <td>Alamat</td>
    </tr>";
    while ($data = mysql_fetch_array($result)) { //fetch the result from query into an array
    echo "
    <tr>
    <td>".$data[‘no’]."</td>
    <td>".$data[‘name’]."</td>
    <td>".$data[‘address’]."</td>
    </tr>";
    }
    echo "</table>";
    ?>
    [/sourcecode]
  2. simpan dengan nama search_exe.php
  3. Penjelasan dapat dilihat di script comment

Step 6 : Testing Code

  1. Pergi ke http://localhost/searching/formsearching.php. Anda akan melihat form seperti dibawah,
  2. Masukkan nama pada field nama (misal nama yang telah diinsert ke DB, yaitu june)
  3. Klik tombol search dan anda akan melihat hasilnya

Selamat berkreasi dengan PHP πŸ˜€ Happy Coding..

Kategori
PHP

Tutorial to Create Simple Tabs-AJAX with AJAX and PHP

Case Study : Create Simple Ajax Application (Ajax Tabs) with PHP
Requirements : Webserver Package, already installed.

Step 1 : Make Work Folder Structure

  1. Create a folder named simpleajax in your documentroot.
  2. Save this gif file below in simpleajax folder (save gif with : right-click and save as). This image used for loader animation, that is image that will showed when doing ajax transactions.
  3. Save all this file in this tutorial on this folder.

Step 2 : Create Index File

  1. Type the following script,
    [sourcecode language=”php”]
    <html>
    <head>
    <title></title>
    <script type="text/javascript" src="ajax.js"></script>
    </head>
    <body>
    <center>
    <h3> Simple AJAX Tabs</h3>
    <div id="tabs">
    <a href="fallback1.php" id="tab1" class="tab" onclick="return handleOnClick(1);"> News 1</a>
    <a href="fallback2.php" id="tab2" class="tab" onclick="return handleOnClick(2);">News 2</a>
    </div>
    <br>
    <div id="content">Klik pada tab untuk mengaktifkannya.</div>
    </center>
    </body>
    </html>
    [/sourcecode]
  2. Save with name index.php
  3. Explanation : Index.php is the main file in this application. The most important for implementing Ajax is in rows 9-14. Each tab has a link on each – each a value attribute href and the onclick event handler, as in the script below,
    [sourcecode language=”php”]<a href="fallback1.php" id="tab1" class="tab" onclick="return handleOnClick(1);"> News 1</a>[/sourcecode]

    In this case, AJAX initialized when user activated the tab by clicking on it.
    When successfully executed AJAX transactions = handleOnClick function () returns false so that it will cancel the click event. AJAX and then control the process of updating the document and the href is not followed.
    When the AJAX transaction failed (XMLHttpRequest object can not be diinstansiasi, in other words, the browser does not support AJAX) = handleOnClick Function returns true and the href is followed, navigate the document in a new document pages (ie fallback pages).

    Why application provides each onClick event handler and a href URLs for each tab?

    This is to overcome if the browser of the device that is used does not support AJAX. So if the device supports AJAX, AJAX transaction to display the contents will be done . However, if not support, the news still displayed but with the lead the new web page (fallback page) contains the same news from the pages generated by the transaction AJAX.

Step 3 : Create ajax.js File

  1. Type the following script,
    [sourcecode language=”javascript”]
    var req = null;
    // Function to obtain an instance of XMLHttpRequest used in an AJAX request
    function getXHR() {
    if (window.XMLHttpRequest) {
    return new XMLHttpRequest();
    }
    else try {
    return new ActiveXObject(‘Msxml2.XMLHTTP’);
    } catch(e) {
    try {
    return new ActiveXObject("Microsoft.XMLHTTP");
    } catch(e) {
    return null;
    }
    }
    }
    // Use AJAX to update the page content.
    // Returns true if the AJAX request succeeded, or false otherwise.
    function updateContent(url, id) {
    req = getXHR();
    if (req != null) {
    // Create a HTTP get request
    req.open(‘GET’, url);
    // Anonymous callback function to handle state changes for the web request
    req.onreadystatechange = function() {
    // State "4" is response received.
    if (req.readyState == 4) {
    // Check for HTTP 200 – successful response from web server
    if (req.status == 200) {
    document.getElementById(id).innerHTML = req.responseText;
    } else {
    document.getElementById(id).innerHTML = ‘Could not retrieve data.’;
    }
    }
    // For all other states, show an animated gif indicating that content is loading
    else {
    document.getElementById(id).innerHTML = ‘<img id="loading" src="flickr-loader.gif"/>’; //result of download step 1
    }
    return false;
    }
    // Start the AJAX transaction
    req.send(”);
    } else {
    return false;
    }
    return true;
    }
    // This is the onClick event handler for the tab links
    // index – the zero-based index of the tab that was clicked
    function handleOnClick(index) {
    // Construct the ID of the clicked tab
    var tabId = "tab" + index;
    // Update the style of the active tab.
    document.getElementById(tabId).setAttribute(‘class’, ‘activeTab’);
    // Update the styles of the inactive tabs. This could also be achieved in a for loop.
    if (index != 1) {
    document.getElementById("tab" + 1).setAttribute(‘class’, ‘tab’);
    }
    if (index != 2) {
    document.getElementById("tab" + 2).setAttribute(‘class’, ‘tab’);
    }
    // Use AJAX to update the "content" div.
    // Construct the URL to use to retrieve the updated content
    var url = "http://localhost/helloMobile/getNews"+index+".php";
    // If the AJAX request succeeded, do not follow the original link
    if (updateContent(url, "content")) {
    return false;
    }
    // If we are here, then the AJAX transaction failed.
    // Follow the link and load the static page.
    return true;
    }
    [/sourcecode]
  2. Save with the name ajax.js
  3. Penjelasan : The primary key of AJAX is the XMLHttpRequest object. The object lies in the browser so that each browser has its own way to create the object. Function getXHR() on ajax.js script above is a function to create an instance of the XMLHttpRequest (XHR), which will be used in AJAX (Note: for IE, ajax support via ActiveX objects, rather than XHR). updateContent function() is a function that will update content of the tab via AJAX, this function will returns true if the AJAX transaction succeeded, and false if it fails.
    After that the function will create a Http get request and check the progress of the update with the onreadystatechange event. onreadystatechange event to run 3 things,

    a. If the asynchronous web request is in progress, then the loading animation will be displayed.
    b. If the AJAX request completed, then the body of the response will be used as web content of the element.
    c. If the AJAX request terminated with an error, the error will be displayed on the user, ie “Could not retrieve data”

    Transactions using the document.getElementById and element.innerHTML AJAX to update the dynamic parts of the document (in this case is the news as a dynamic part of the web).

    Function handleOnClick () is a function of event handler when the tab is clicked. This function uses the parameter index, according to the index of the tab is clicked by the user. This function will update the styling of tabs (to distinguish active tabs and inactive) and update the contents of the div content. The contents of the div content is news files according to the tab the user clicked. Content is obtainable from URL var url = “http://localhost/simpleajax/getNews” + index + “.php”;
    So the script is going to retrieve a page from getNews (index) using AJAX, in accordance with the index of the tab is clicked by the user.

Step 4 : Create get News File

  1. Type the following script,
    [sourcecode language=”php”]
    <?php
    sleep(2);
    echo "News 1";
    echo "Ini adalah isi berita 1";
    ?>
    [/sourcecode]
  2. Save with the name getNews1.php
  3. Then type the following script,
    [sourcecode language=”php”]
    <?php
    sleep(2);
    echo "News 2";
    echo "Ini adalah isi berita 2";
    ?>
    [/sourcecode]
  4. Save with the name getNews2.php
  5. Explanations : Two of these files is the original link (which is executed via AJAX) from the first and second tabs (tab berindex 1 and 2). So getNews1.php and getNews2.php will be executed when the user clicks on the tab index 1 and 2, and the browser used supports AJAX.

Step 5 : Create the fallback File

  1. Type the following script,
    [sourcecode language=”php”]
    <html>
    <head>
    <title></title>
    <script type="text/javascript" src="ajax.js"></script>
    </head>
    <body>
    <center>
    <h3> Simple AJAX Tabs</h3>
    <div id="tabs">
    <a href="fallback1.php" id="tab1" class="tab" onclick="return handleOnClick(1);"> News 1</a>
    <a href="fallback2.php" id="tab2" class="tab" onclick="return handleOnClick(2);">News 2</a>
    </div>
    <div id="content">
    <?php echo "News 1";
    echo "Ini adalah isi berita 1";
    ?>
    </div>
    </center>
    </body>
    </html>
    [/sourcecode]
  2. Save with the name fallback1.php
  3. Then type the following script,
    [sourcecode language=”php”]
    <html>
    <head>
    <title></title>
    <script type="text/javascript" src="ajax2.js"></script>
    </head>
    <body>
    <center>
    <h3> Simple AJAX Tabs</h3>
    <div id="tabs">
    <a href="fallback1.php" id="tab1" class="tab" onclick="return handleOnClick(1);"> News 1</a>
    <a href="fallback2.php" id="tab2" class="tab" onclick="return handleOnClick(2);">News 2</a>
    </div>
    <div id="content">
    <?php echo "News 2";
    echo "Ini adalah isi berita 2";
    ?>
    </div>
    </center>
    </body>
    </html>
    [/sourcecode]
  4. Save with the name fallback2.php
  5. Explanation : File fallback1.php and fallback2.php a static webpage files that will be executed when user clicks on the tab index 1 and 2, and the browser used does NOT support AJAX. So the news is still displayed but in a different way (not using AJAX).

Step 6 : Testing Code

  1. Go to http://localhost/simpleajax/
  2. Then index.php file will be showed, like the picture below,
  3. Click on one tab, so of the browser supports AJAX, loader animation will be showed. See picture.
  4. After the loading done, maka isi dari tab tersebut akan ditampilkan (dari getNews.php)
  5. Try to turnoff AJAX support in the browser (that is with non-activated javascript browser – For Firefox, it is with tools – options – content – remove the check mark on activated javascript ). See picture below.
  6. Try again with click on another tab.
  7. The news will be showed without loader animation (without AJAX) from fallback.php

Okay, be creative with AJAX πŸ™‚ Happy AJAX-ing πŸ™‚

Kategori
PHP

Tutorial Membuat AJAX-Tab Sederhana dengan AJAX dan PHP

Studi Kasus : Membuat contoh aplikasi AJAX sederhana (Tab Ajax) dengan PHP

Kebutuhan : Webserver Package, already installed.

Step 1 : Membuat struktur folder kerja

  1. Siapkan folder dengan nama simpleajax pada folder document root anda.
  2. Simpan file gif berikut ini pada folder simpleajax (simpan gambar dengan cara : klik pada gambar dan save as). Gambar ini akan digunakan sebagai loader animation, yaitu gambar yang akan ditampilkan ketika transaksi ajax sedang dilakukan.
  3. Simpan semua file pada praktikum hari ini pada folder ini.

Step 2 : Membuat file Index

  1. Ketikkan script berikut,
    [sourcecode language=”php”]
    <html>
    <head>
    <title></title>
    <script type="text/javascript" src="ajax.js"></script>
    </head>
    <body>
    <center>
    <h3> Simple AJAX Tabs</h3>
    <div id="tabs">
    <a href="fallback1.php" id="tab1" class="tab" onclick="return handleOnClick(1);"> News 1</a>
    <a href="fallback2.php" id="tab2" class="tab" onclick="return handleOnClick(2);">News 2</a>
    </div>
    <br>
    <div id="content">Klik pada tab untuk mengaktifkannya.</div>
    </center>
    </body>
    </html>
    [/sourcecode]
  2. Simpan dengan nama index.php
  3. Penjelasan : Index.php adalah file utama dalam aplikasi ini. Bagian yang paling penting untuk implementasi Ajax adalah pada baris 9 – 14. Setiap link pada tab memiliki masing – masing sebuah atribut value href dan onclick event handler, seperti pada script dibawah,
    [sourcecode language=”php”]<a href="fallback1.php" id="tab1" class="tab" onclick="return handleOnClick(1);"> News 1</a>[/sourcecode]

    Pada kasus ini, AJAX diinisiasi ketika user mengaktifkan tab dengan meng-kliknya.

    Ketika transaksi AJAX berhasil dieksekusi = fungsi handleOnClick() mengembalikan nilai false sehingga akan membatalkan event klik. AJAX kemudian mengontrol proses update pada dokumen dan href tidak diikuti.
    Ketika transaksi AJAX gagal (XMLHttpRequest objek tidak dapat diinstansiasi, dengan kata lain browser tidak support AJAX) = Fungsi handleOnClick mengembalikan nilai true dan href diikuti, menavigasi dokumen pada halaman dokumen baru (yaitu halaman fallback).

    Kenapa aplikasi menyediakan masing-masing event handler onClick dan sebuah href URL untuk setiap tab?

    Hal ini untuk mengatasi apabila browser dari device yang digunakan tidak mensupport AJAX. Jadi apabila device mensupport AJAX, transaksi AJAX untuk menampilkan berita akan dilakukan. Namun apabila tidak support, berita tetap ditampilkan tetapi dengan mengarahkannya pada halaman web baru (halaman fallback) berisi berita yang sama dari halaman yang dihasilkan oleh transaksi AJAX.

Step 3 : Membuat file ajax.js

  1. Ketikkan script berikut,
    [sourcecode language=”javascript”]
    var req = null;
    // Function to obtain an instance of XMLHttpRequest used in an AJAX request
    function getXHR() {
    if (window.XMLHttpRequest) {
    return new XMLHttpRequest();
    }
    else try {
    return new ActiveXObject(‘Msxml2.XMLHTTP’);
    } catch(e) {
    try {
    return new ActiveXObject("Microsoft.XMLHTTP");
    } catch(e) {
    return null;
    }
    }
    }
    // Use AJAX to update the page content.
    // Returns true if the AJAX request succeeded, or false otherwise.
    function updateContent(url, id) {
    req = getXHR();
    if (req != null) {
    // Create a HTTP get request
    req.open(‘GET’, url);
    // Anonymous callback function to handle state changes for the web request
    req.onreadystatechange = function() {
    // State "4" is response received.
    if (req.readyState == 4) {
    // Check for HTTP 200 – successful response from web server
    if (req.status == 200) {
    document.getElementById(id).innerHTML = req.responseText;
    } else {
    document.getElementById(id).innerHTML = ‘Could not retrieve data.’;
    }
    }
    // For all other states, show an animated gif indicating that content is loading
    else {
    document.getElementById(id).innerHTML = ‘<img id="loading" src="flickr-loader.gif"/>’; //result of download step 1
    }
    return false;
    }
    // Start the AJAX transaction
    req.send(”);
    } else {
    return false;
    }
    return true;
    }
    // This is the onClick event handler for the tab links
    // index – the zero-based index of the tab that was clicked
    function handleOnClick(index) {
    // Construct the ID of the clicked tab
    var tabId = "tab" + index;
    // Update the style of the active tab.
    document.getElementById(tabId).setAttribute(‘class’, ‘activeTab’);
    // Update the styles of the inactive tabs. This could also be achieved in a for loop.
    if (index != 1) {
    document.getElementById("tab" + 1).setAttribute(‘class’, ‘tab’);
    }
    if (index != 2) {
    document.getElementById("tab" + 2).setAttribute(‘class’, ‘tab’);
    }
    // Use AJAX to update the "content" div.
    // Construct the URL to use to retrieve the updated content
    var url = "http://localhost/helloMobile/getNews"+index+".php";
    // If the AJAX request succeeded, do not follow the original link
    if (updateContent(url, "content")) {
    return false;
    }
    // If we are here, then the AJAX transaction failed.
    // Follow the link and load the static page.
    return true;
    }
    [/sourcecode]
  2. Simpan dengan nama ajax.js
  3. Penjelasan : Kunci utama dari AJAX adalah objek XMLHttpRequest. Objek tersebut terletak pada browser sehingga masing – masing browser memiliki cara tersendiri untuk membuat objek tersebut. Function getXHR() pada script ajax2.js diatas adalah fungsi untuk menciptakan instance dari XMLHttpRequest (XHR) yang akan digunakan pada AJAX (Catatan : untuk IE, mensupport ajax via ActiveX objects, bukan XHR).Function updateContent() merupakan fungsi yang akan mengupdate content dari tab via AJAX, fungsi ini akan mengembalikan nilai true apabila transaksi AJAX berhasil, dan false jika gagal.
    Setelah itu fungsi akan menciptakan Http get request dan mengecek progress dari update dengan onreadystatechange event.
    onreadystatechange event menjalankan 3 hal,
    a. Jika asynchronous web request sedang dalam progress, maka animasi loading akan ditampilkan.
    b. Jika AJAX request completed, maka body dari web response akan digunakan sebagai content dari elemen.
    c. Jika AJAX request terminate dengan sebuah eror, maka eror akan ditampilkan pada user, yaitu β€œCould not retrieve data”Transaksi AJAX menggunakan document.getElementById dan element.innerHTML untuk mengupdate bagian dinamis dari dokumen (dalam kasus ini adalah berita sebagai bagian dinamis dari mobile web).

    Function handleOnClick() merupakan fungsi event handler ketika tab di klik. Fungsi ini menggunakan parameter index, sesuai dengan index dari tab yang diklik oleh user. Fungsi ini akan mengupdate style dari tab (untuk membedakan tab yang aktif dan yang tidak aktif) dan mengupdate isi dari div content. Isi dari div content merupakan file berita sesuai dengan tab yang diklik user. Content ini didapat dari URL var url = “http://localhost/simpleajax/getNews”+index+”.php”;
    Jadi script tersebut akan me-retrieve halaman dari getNews(index) dengan menggunakan AJAX, sesuai dengan index dari tab yang diklik oleh user.

Step 4 : Membuat file get News

  1. Ketikkan script berikut,
    [sourcecode language=”php”]
    <?php
    sleep(2);
    echo "News 1";
    echo "Ini adalah isi berita 1";
    ?>
    [/sourcecode]
  2. Simpan dengan nama getNews1.php
  3. Kemudian ketiikan script berikut,
    [sourcecode language=”php”]
    <?php
    sleep(2);
    echo "News 2";
    echo "Ini adalah isi berita 2";
    ?>
    [/sourcecode]
  4. Simpan dengan nama getNews2.php
  5. Penjelasan : Dua file ini merupakan original link (yang dijalankan via AJAX) dari tab pertama dan kedua (tab berindex 1 dan 2). Jadi getNews1.php dan getNews2.php akan dijalankan apabila user meng-klik tab index 1 dan 2, serta browser yang digunakan mensupport AJAX.

Step 5 : Membuat file fallback

  1. Ketikkan script berikut,
    [sourcecode language=”php”]
    <html>
    <head>
    <title></title>
    <script type="text/javascript" src="ajax.js"></script>
    </head>
    <body>
    <center>
    <h3> Simple AJAX Tabs</h3>
    <div id="tabs">
    <a href="fallback1.php" id="tab1" class="tab" onclick="return handleOnClick(1);"> News 1</a>
    <a href="fallback2.php" id="tab2" class="tab" onclick="return handleOnClick(2);">News 2</a>
    </div>
    <div id="content">
    <?php echo "News 1";
    echo "Ini adalah isi berita 1";
    ?>
    </div>
    </center>
    </body>
    </html>
    [/sourcecode]
  2. Simpan dengan nama fallback1.php
  3. Kemudian ketiikan script berikut,
    [sourcecode language=”php”]
    <html>
    <head>
    <title></title>
    <script type="text/javascript" src="ajax2.js"></script>
    </head>
    <body>
    <center>
    <h3> Simple AJAX Tabs</h3>
    <div id="tabs">
    <a href="fallback1.php" id="tab1" class="tab" onclick="return handleOnClick(1);"> News 1</a>
    <a href="fallback2.php" id="tab2" class="tab" onclick="return handleOnClick(2);">News 2</a>
    </div>
    <div id="content">
    <?php echo "News 2";
    echo "Ini adalah isi berita 2";
    ?>
    </div>
    </center>
    </body>
    </html>
    [/sourcecode]
  4. Simpan dengan nama fallback2.php
  5. Penjelasan : File fallback1.php dan fallback2.php merupakan file webpage statis yang akan dijalankan apabila user meng-klik tab index 1 dan 2, serta browser yang digunakan TIDAK mensupport AJAX. Jadi berita tetap ditampilkan namun dengan cara yang berbeda (tidak menggunakan AJAX).

Step 6 : Testing Code

  1. Pergi ke http://localhost/simpleajax/
  2. Maka file index.php akan ditampilkan, seperti gambar dibawah ini,
  3. Klik pada salah satu tab, maka jika browser anda support ajax, animasi loading akan ditampilkan. Lihat gambar dibawah.
  4. Setelah loading selesai, maka isi dari tab tersebut akan ditampilkan (dari getNews.php)
  5. Coba matikan ajax pada browser anda (dengan me-nonaktifkan javascript browser – untuk browser Firefox, caranya adalah dengan klik tools – options – content – hilangkan tanda centang pada activated javascript ). Lihat gambar dibawah.
  6. Coba lagi dengan mengklik salah satu tab.
  7. Maka berita akan ditampilkan tanpa animasi loading (without AJAX) dari file fallback.php

Okay, silahkan berkreasi dengan AJAX πŸ™‚ Happy AJAX-ing πŸ™‚

Kategori
Wordpress Plugins

Easy-Posting a Source Code in the WordPress with SyntaxHighlighter

Case Study : Using SyntaxHighlighter plugin to write source code in the WordPress post.

Requirements : WordPress bundle, download here. and SyntaxHighlighter, download here.

Sometimes, we will need to write a sourcecode in our WordPress. This is if we write some tutorial about some programming language. WordPress it self actually already provide some facilities to write a sourcecode, for example :

<code> your code here </code>

Actuallt, this facilities run well in showing your code, but maybe you wont like it because it isn’t quite good-looking. Too small, and have a same colour for every code. Just like this,

If you really isn’t like with this, may you can use this plugin. Syntax Highlighter. Write a source code with this plugin will give some advantages,

  1. There are numbering in front of every line of code –> This will help you if you want to give an explanation in every code.
  2. Colorfull code
  3. Standard font size
  4. Customizable (self-settingi). For example, you can give a highlight in the code.


Step 1 : Syntax Highlighter Installation

  1. Download syntaxhighlighter plugin from here
  2. Start the installation. Login to your WordPress, you will be redirected in to dashboard page
  3. Choose Plugins menu in the left side WordPress page.
  4. Choose Add New tab
  5. In the Install Plugin menu, choose Upload tab.
  6. Browse file zip syntaxhighlighter plugin from download, then click Install Now
  7. So it will show install conformation success like the image below.
  8. Click Activate Plugin to activated the plugin .


Step 2 : Using the Plugin

  1. Create a new post with click menu Posts – Add New
  2. Type this sample in the HTML editor page (NOT the Visual Editor page). See the red circle in the picture,

  3. Just like that. Choose publish and you will see the picture below,

This plugin support for actionscript3, bash, coldfusion, cpp, csharp, php, css, xml, javascript, java, perl, sql.. till phyton πŸ˜€ For the full language which supported by this plugin, go here.

Step 3 : Plugin Customization

With this plugin, you can customize the appearance of sourcecode with several optional option. One option is that you can optionally give highlights on certain lines of code. For example,

Code –>

Result–>

And there are many optional choices that you can try it yourself. You can find a wide selection of optional here.
Happy trying πŸ˜€ happy WordPress-ing πŸ˜€

Kategori
Wordpress Plugins

Posting Source Code dalam WordPress MUDAH dengan SyntaxHighlighter

Studi Kasus : Menggunakan plugin SyntaxHighlighter untuk menulis kode program dalam postingan WordPress

Requirements : WordPress bundle, download here. and SyntaxHighlighter, download here.

Adakalanya kita akan membutuhkan untuk menulis kode program (sourcecode) dalam postingan di WordPress kita. Hal ini misalkan ketika kita menulis suatu tutorial untuk bahasa pemrograman tertentu. WordPress sendiri sebenarnya telah menyediakan fasilitas untuk menuliskan kode program seperti ini yaitu dengan menggunakan syntax,

<code> your code here </code>

Sebenarnya fasilitas tersebut dapat berjalan dengan baik dalam menampilkan kode anda, namun mungkin anda tidak akan begitu menyukainya karena tampilannya yang… tidak begitu bagus. Kecil kecil, dan berwarna sama untuk semua kode. Seperti ini,

Kalau anda memang tidak menyukai hal tersebut, mungkin anda harus mencoba plugin WordPress satu ini. Syntax Highlighter. Menulis kode program menggunakan plugin ini akan memberi keuntungan diantaranya,

  1. Terdapat penomoran didepan setiap baris code –> Hal ini memudahkan apabila anda ingin memberi penjalasan terhadap kode tersebut.
  2. Berwarna-warni –> Jadi akan lebih jelas bagian kodenya, mana yang merupakan variabel, mana yang komentar, dll
  3. Ukuran font standar –> Enak dibaca. Tidak terlihat njlimet seperti kode program biasanya πŸ˜€
  4. Bisa dikustomisasi (diatur sendiri) dengan banyak pilihan opsional. Misal, code bisa diberi highlight.


Step 1 : Instalasi Syntax Highlighter

  1. Download plugin syntaxhighlighter dari sini
  2. Mulai instalasi. Login ke halaman wordpress anda, maka anda akan diarahkan ke halaman dashboard
  3. Pilih menu Plugins pada samping kiri halaman WordPress anda.
  4. Pilih tab Add New
  5. Pada menu Install Plugin, pilih tab Upload.
  6. Browse file zip syntaxhighlighter plugin hasil download, kemudian klik Install Now
  7. Maka akan ditampilkan konfirmasi sukses instal seperti gambar dibawah.
  8. Klik Activate Plugin untuk langsung mengaktifkan plugin tersebut.


Step 2 : Penggunaan Plugin

  1. Lakukan posting baru dengan memilih menu Posts – Add New
  2. Ketikkan contoh berikut ini pada halaman HTML editor (bukan halaman Visual Editor). Lihat gambar dilingkari merah,

  3. Sesimple itu saja. Pilih publish dan anda akan melihat tampilan seperti berikut,

Untul lebih lengkapnya plugin ini mendukung bahasa pemrograman mulai dari actionscript3, bash, coldfusion, cpp, csharp, php, css, xml, javascript, java, perl, sql.. hingga phyton πŸ˜€ untuk lebih lengkapnya plugin ini mendukung bahasa apa saja lihat disini.

Step 3 : Kustomisasi Plugin

Dengan plugin ini, anda juga bisa mens-kustomisasi tampilan source code dengan berbagai pilihan opsional. Salah satu pilihan opsional adalah anda bisa memberi highlight pada baris tertentu pada code. Contoh,

Code –>

Hasil –>

Dan masih banyak pilihan opsional yang bisa anda coba sendiri. Anda bisa mengetahui berbagai pilihan opsional tersebut di sini.

Selamat mencoba πŸ˜€ happy WordPress-ing πŸ˜€

Kategori
PHP

Export from Database to Excel File in the CodeIgniter

Case Study : Export from Database (Mysql) to Excel File in the CodeIgniter

Requirements : Webserver Package, already installed. CodeIgniter.

Export data is needed if we are developing an application, especially for the office applications. Most of the offices are still using excel to manage their data, because Excel is one of the earliest applications used to manage office data.

Step 1 : CI Configuration

  1. Open the config.php file located in the system-application-config
  2. Change base_url, adjust according where your ci folder are. FOr example: your ci folder located in www/ci folder
    so change the line $config['base_url']="http://example.com/";
    with
    $config['base_url']="http://localhost/ci";
  3. Setting the database. Open file database.php located in the same folder as config.php. Change hostname, username, password, and the database name according to your mysql setting. For example :
    $db['default']['hostname'] = "localhost";
    $db['default']['username'] = "root";
    $db['default']['password'] = "";
    $db['default']['database'] = "db_tutorial";

Step 2 : Prepare the Database

  1. Make a database named db_tutorial.
  2. Prepare a table named tb_book (for table’s structure, see picture below)
  3. Insert some sample data, for example insert some sample data just like the picture below
  4. Ok, we’re done with database !

Step 3 : Create the Controller

  1. Type the following script,
    [sourcecode language=”php”]
    <?php
    class Buku_con extends Controller {
    public function Buku_con() {
    parent::__construct();
    $this->load->model(‘buku_model’);//load the model
    $this->load->library(‘pagination’);
    }
    //function to get the data from tb_book
    function getBuku() {
    $data[‘title’] = ‘menampilkan isi buku’;
    $data[‘detail’] = $this->buku_model->getBuku();//call the model and save the result in $detail
    $this->load->view(‘buku_view’, $data);
    }
    //function to export to excel
    function toExcelAll() {
    $query[‘data1’] = $this->buku_model->ToExcelAll();
    $this->load->view(‘excel_view’,$query);
    }
    }
    ?>[/sourcecode]
  2. Save with the name buku_con.php in the system-application-controllers folder
  3. Penjelasan :See at the script’s comment.

Step 4 : Create the Model

  1. Type the following script,
    [sourcecode language=”php”]
    <?php
    class Buku_model extends Model {
    function Buku_model() {
    parent::Model();
    }
    function getBuku() {
    $this->db->select(‘*’);
    $this->db->from(‘tb_book’);
    $this->db->order_by(‘id’,’DESC’);
    $getData = $this->db->get();
    if($getData->num_rows() > 0)
    return $getData->result_array();
    else
    return null;
    }
    //query for get all data
    function toExcelAll() {
    $this->db->select(‘*’);
    $this->db->from(‘tb_book’);
    $this->db->order_by(‘id’,’desc’);
    $getData = $this->db->get();
    if($getData->num_rows() > 0)
    return $getData->result_array();
    else
    return null;
    }
    }
    ?>
    [/sourcecode]
  2. Save with the name buku_model.php in the system-application-models folder

Step 5 : Create the View (View for showing the export link)

  1. Type the following script,
    [sourcecode language=”php”]
    <h4>Book Data</h4>
    <?php if(count($detail) > 0) { ?>
    <table border="1">
    <tr>
    <th>ID</th>
    <th>Title</th>
    <th>Author</th>
    </tr>
    <?php
    foreach($detail as $rows) {
    echo "<tr>";
    echo "
    <td>". $rows[‘id’]."</td>
    <td>". $rows[‘title’] ."</td>
    <td>". $rows[‘author’] ."</td>
    "; } ?>
    </table>
    <?php } ?>
    <br> <br>
    <a href=’toExcelAll’><span style=’color:green;’>Export All Data</span></a>
    [/sourcecode]
  2. Save with the name buku_view.php in the system-application-views folder
  3. Explanation: $detail taken from controller, this variabel filled with the content of tb_book (the model’s result), and then the data showed in the array form.

Step 6 : Create the View (View for setting and formatting Excel File)

  1. Type the following script,
    [sourcecode language=”php”]
    <?php
    header("Content-type: application/octet-stream");
    header("Content-Disposition: attachment; filename=exceldata.xls");
    header("Pragma: no-cache");
    header("Expires: 0");
    ?>
    <table border=’1′ width="70%">
    <tr>
    <td>ID</td>
    <td>TITLE</td>
    <td>AUTHOR</td>
    </tr>
    <?
    foreach($data1 as $item) {
    ?>
    <tr>
    <td><?=$item[‘id’]?></td>
    <td><?=$item[‘title’]?></td>
    <td><?=$item[‘author’]?></td>
    </tr>
    <? } ?>
    </table>
    [/sourcecode]
  2. Save with the name excel_view.php in the system-application-views folder

Step 7 : Testing the Code

  1. Go to http://localhost/namaFolderCIKamu/buku_con/getBuku
  2. You will see something like this,
  3. Click on the Export All Data link, the browser will automatic download the excel file
  4. Open the excel file, and you will see the content from tb_book πŸ™‚

Happy Trying πŸ™‚ Happy Coding πŸ™‚

Kategori
PHP

Export dari Database ke File Excel dalam CodeIgniter

Studi Kasus : Melakukan Export data dari Database (Mysql) ke file Excel dalam CodeIgniter

Requirements : Webserver Package, already installed. CodeIgniter.

Export data sangat dibutuhkan apabila kita mendevelop aplikasi, terutama untuk aplikasi perkantoran. Sebagian besar perkantoran masih menggunakan excel untuk memanage data mereka, karena excel memang salah satu aplikasi paling awal yang digunakan untuk memanajemen data perkantoran.

Step 1 : Konfigurasi CI

  1. Buka file config.php yang berada dalam folder system-application-config-config.php
  2. Ubah base url, sesuaikan dengan lokasi dimana folder CI-mu berada (tempat ekstrak-an tadi). Contoh : Folder CI anda berada dalam folder www/ci
    maka ubah baris $config['base_url']="http://example.com/";
    dengan
    $config['base_url'] = "http://localhost/ci/";
  3. Setting database. Buka file database.php yang berada dalam folder yang sama dengan config.php. Ubah hostname, username, password, dan nama database. Sesuaikan dengan pengaturan mysql anda. Contoh :
    $db['default']['hostname'] = "localhost";
    $db['default']['username'] = "root";
    $db['default']['password'] = "";
    $db['default']['database'] = "db_tutorial";

Step 2 : Siapkan Database

  1. Buat database dengan nama db_tutorial (via phpmyadmin)
  2. Siapkan tabel dengan nama tb_book (untuk strukturnya, lihat gambar dibawah ini)
  3. Insertkan beberapa sample data, sebagai contoh insertkan data seperti tabel dibawah ini.
  4. Ok, we’re done with database !

Step 3 : Membuat Controller

  1. Ketikkan script berikut,
    [sourcecode language=”php”]
    <?php
    class Buku_con extends Controller {
    public function Buku_con() {
    parent::__construct();
    $this->load->model(‘buku_model’);//load the model
    $this->load->library(‘pagination’);
    }
    //function to get the data from tb_book
    function getBuku() {
    $data[‘title’] = ‘menampilkan isi buku’;
    $data[‘detail’] = $this->buku_model->getBuku();//call the model and save the result in $detail
    $this->load->view(‘buku_view’, $data);
    }
    //function to export to excel
    function toExcelAll() {
    $query[‘data1’] = $this->buku_model->ToExcelAll();
    $this->load->view(‘excel_view’,$query);
    }
    }
    ?>[/sourcecode]
  2. Simpan dengan nama buku_con dalam folder system-application-controllers
  3. Penjelasan :Lihat di komen script.

Step 4 : Membuat Model

  1. Ketikkan script berikut,
    [sourcecode language=”php”]
    <?php
    class Buku_model extends Model {
    function Buku_model() {
    parent::Model();
    }
    function getBuku() {
    $this->db->select(‘*’);
    $this->db->from(‘tb_book’);
    $this->db->order_by(‘id’,’DESC’);
    $getData = $this->db->get();
    if($getData->num_rows() > 0)
    return $getData->result_array();
    else
    return null;
    }
    //query for get all data
    function toExcelAll() {
    $this->db->select(‘*’);
    $this->db->from(‘tb_book’);
    $this->db->order_by(‘id’,’desc’);
    $getData = $this->db->get();
    if($getData->num_rows() > 0)
    return $getData->result_array();
    else
    return null;
    }
    }
    ?>
    [/sourcecode]
  2. Simpan dalam folder system-application-models, dengan nama buku_model.php

Step 5 : Membuat View (yang menampilkan link untuk export)

  1. Ketikkan script berikut,
    [sourcecode language=”php”]
    <h4>Book Data</h4>
    <?php if(count($detail) > 0) { ?>
    <table border="1">
    <tr>
    <th>ID</th>
    <th>Title</th>
    <th>Author</th>
    </tr>
    <?php
    foreach($detail as $rows) {
    echo "<tr>";
    echo "
    <td>". $rows[‘id’]."</td>
    <td>". $rows[‘title’] ."</td>
    <td>". $rows[‘author’] ."</td>
    "; } ?>
    </table>
    <?php } ?>
    <br> <br>
    <a href=’toExcelAll’><span style=’color:green;’>Export All Data</span></a>
    [/sourcecode]
  2. Simpan dalam folder system-application-views, dengan nama buku_view.php
  3. Penjelasan : $detail didapatkan dari controller, variabel ini berisi data dari tb_book (hasil dari model). Kemudian data ditampilkan dalam bentuk arrays.

Step 6 : Membuat View (view untuk menconvert ke excel)

  1. Ketikkan script berikut,
    [sourcecode language=”php”]
    <?php
    header("Content-type: application/octet-stream");
    header("Content-Disposition: attachment; filename=exceldata.xls");
    header("Pragma: no-cache");
    header("Expires: 0");
    ?>
    <table border=’1′ width="70%">
    <tr>
    <td>ID</td>
    <td>TITLE</td>
    <td>AUTHOR</td>
    </tr>
    <?
    foreach($data1 as $item) {
    ?>
    <tr>
    <td><?=$item[‘id’]?></td>
    <td><?=$item[‘title’]?></td>
    <td><?=$item[‘author’]?></td>
    </tr>
    <? } ?>
    </table>
    [/sourcecode]
  2. Simpan dalam folder system-application-views, dengan nama excel_view.php

Step 7 : Testing Code

  1. Buka browser, pergi ke http://localhost/namaFolderCIKamu/buku_con/getBuku
  2. Anda akan melihat tampilan seperti berikut,
  3. Klik pada link Export to excell, maka browser akan otomatis mendownload file excel,
  4. Buka file excel yang telah di download, maka data dari tb_book akan ditampilkan πŸ™‚

Silahkan mencoba πŸ™‚ Happy Coding πŸ™‚

Kategori
PHP

Simple MD5 Login System (+Logout) with CodeIgniter

Case Study : Create Simple MD5 Login System (+Logout) with CodeIgniter

Requirements: Webserver Package, already installed. CodeIgniter bundle.

Login (and Logout) is almost exist in any application that developed with certain programming language, in this case is PHP with framework CodeIgniter. The very basic concept of login is matching the username and password from user with the ones that are in the databases. With a security reason, usually the password is encoded using MD5. MD5 is one of hash function (one-way) that quite popular in cryptography, usually for user autentification.

On the other hand, logout has the simplest basic concept, that is with destroy the user’s session.

Anyway… just let trying it πŸ™‚

Step 1 : CI Configuration (always start with it)

  1. Open the config.php file located in the system-application-config
  2. Change base_url, adjust according where your ci folder are. FOr example: your ci folder located in www/ci folder
    so change the line $config['base_url']="http://example.com/";
    with
    $config['base_url']="http://localhost/ci";
  3. Setting the database. Open file database.php located in the same folder as config.php. Change hostname, username, password, and the database name according to your mysql setting. For example :
    $db['default']['hostname'] = "localhost";
    $db['default']['username'] = "root";
    $db['default']['password'] = "";
    $db['default']['database'] = "db_tutorial";

Step 2 : Prepare the Database

  1. Make a database named db_tutorial.
  2. Prepare a table named tb_book (for table’s structure, see picture below)
  3. Insert some sample data, for example insert some sample data just like the picture below (REMEMBER : when you inserting some sample data, use MD5 function in to password field —> see the red circle on the picture)
  4. This is the result of sample data (with MD5 password)
  5. Ok, we’re done with database !

Step 3 : Create the Login Form (view)

  1. Type the following script,
    [sourcecode language=”php”]
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html><head>
    <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
    <title>Login with CI</title>
    <center>
    <h2> <b> Login with CI </b> <h2>
    <form action="<?=base_url();?>login/proseslogin" method="post">
    <table border="0" align="center">
    <tr>
    <td> Username</td>
    <td> <input name="username" type="text"> </td>
    </tr>
    <tr>
    <td> Password</td>
    <td> <input name="password" type="password"> </td>
    </tr>
    <tr>
    <td> &nbsp; </td>
    <td> <input name="submit" type="submit" value="login"> </td>
    </tr>
    </table>
    </form>
    <?php if(isset($error)) echo "<b><span style=’color:red;’>$error</span></b>";
    if(isset($logout)) echo "<b><span style=’color:red;’>$logout</span></b>"; ?>
    </center>
    </body></html>
    [/sourcecode]
  2. Save with the name login_view.php in the system-application-views folder

Step 4 : Create the Processing Controller for Login+Logout

  1. Type the following script,
    [sourcecode language=”php”]
    <?php
    class Login extends Controller {
    //constructor
    function login() {
    parent::Controller();
    $this->load->helper(‘url’);
    $this->load->helper(‘form’);
    $this->load->library(‘form_validation’);
    $this->load->library(‘session’);
    }
    //index for showing the login form
    function index() {
    $this->load->view(‘login_view’);
    }
    //this function will do the login process
    function proseslogin() {
    $username = $this->input->post(‘username’); //read the username that filled by the user
    $password = $this->input->post(‘password’); //read the password that filled by the user
    $passwordx = md5($password); //this is for change $password into MD5 form
    //the query is to matching the username+password user with username+password from database
    $q = $this->db->query("SELECT * FROM tb_user WHERE username=’$username’ AND userpass=’$passwordx’");
    if ($q->num_rows() == 1) {
    // if the query is TRUE, then save the username into session and load the welcome view
    $nama = $q->row()->username;
    $this->session->set_userdata(‘username’,$nama);
    $data[‘welcome’] = "Welcome $nama";
    $this->load->view(‘welcome_view’, $data);
    }
    else {
    // query error
    $data[‘error’]=’!! Wrong Username or Password !!’;
    $this->load->view(‘login_view’, $data);
    }
    }
    //to do logout process
    function logout() {
    $this->session->sess_destroy();
    $data[‘logout’] = ‘You have been logged out.’;
    $this->load->view(‘login_view’, $data);
    }
    }
    ?>
    [/sourcecode]
  2. Save with the name login.php in the system-application-controllers folder
  3. Penjelasan :See at the script’s comment.

Step 4 : Create the Success View

  1. Type the following script,
    [sourcecode language=”php”]
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html><head>
    <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
    <title>Login with CI</title>
    <center>
    <?php if(isset($welcome)) echo "<h2><span style=’color:red;’>$welcome</span></h2>";
    echo "<br/>";
    echo anchor("login/logout", ‘Logout’) ?>
    </center>
    </body></html>
    [/sourcecode]
  2. Save with the name welcome_view.php in the system-application-views folder

Step 7 : Testing the Code

  1. Go to http://localhost/namaFolderCIKamu/login
  2. You will see something like this,
  3. Insert the correct username+password, that is the one in the database (username : june, password : june)
  4. You will be redirected into success login page, that is welcome page like in the picture below,
  5. Click logout to logout from welcome page.
  6. Now insert the wrong username+password (for example username : admin, password : admin)
  7. The warning will shown like below.

Okay, Happy Coding πŸ™‚

Kategori
PHP

Sistem Login simple MD5 (+Logout) dengan CodeIgniter

Studi Kasus : Membuat sistem login (+logout) dengan codeigniter

Kebutuhan : Webserver Package, already installed. CodeIgniter bundle.

Login (dan juga Logout) hampir selalu ada dalam semua sistem / aplikasi yang didevelop dengan bahasa pemrograman tertentu, dalam kasus kali ini adalah PHP dengan framework CodeIgniter. Konsep dasar dari Login adalah mencocokkan username dan password yang dimasukkan oleh user dengan daftar username+password yang tersimpan dalam database. Dengan alasan keamanan, biasanya password disimpan dalam database dengan menggunakan fungsi MD5. MD5 adalah salah satu fungsi hash (satu arah) yang cukup terkenal dalam kriptografi, biasa digunakan untuk autentifikasi user.

Sedangkan Logout memiliki konsep dasar yang cukup sederhana, yaitu dengan men-destroy session dari user yang login tersebut.

Anyway… just let trying it πŸ™‚

Step 1 : Konfigurasi CI (selalu dimulai dengan ini)

  1. Buka file config.php yang berada dalam folder system-application-config-config.php
  2. Ubah base url, sesuaikan dengan lokasi dimana folder CI-mu berada (tempat ekstrak-an tadi). Contoh : Folder CI anda berada dalam folder www/cimaka ubah baris $config['base_url']="http://example.com/";dengan
    $config['base_url'] = "http://localhost/ci/";
  3. Setting database. Buka file database.php yang berada dalam folder yang sama dengan config.php. Ubah hostname, username, password, dan nama database. Sesuaikan dengan pengaturan mysql anda. Contoh :
    $db['default']['hostname'] = "localhost";
    $db['default']['username'] = "root";
    $db['default']['password'] = "";
    $db['default']['database'] = "db_tutorial";

Step 2 : Siapkan Database

  1. Buat database dengan nama db_tutorial (via phpmyadmin)
  2. Siapkan tabel dengan nama tb_user (untuk strukturnya, lihat gambar dibawah ini)
  3. Insertkan beberapa sample data untuk user yang akan login, sebagai contoh insertkan data seperti tabel dibawah ini. INGAT : ketika memasukkan password, pilih fungsi MD5 (lihat gambar dilingkari merah)
  4. Maka hasil dari insert sample data (dengan password dikenai fungsi MD5) adalah seperti gambar dibawah,
  5. Done with database !

Step 3 : Membuat Form Login (view)

  1. Ketikkan script berikut,
    [sourcecode language=”php”]
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html><head>
    <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
    <title>Login with CI</title>
    <center>
    <h2> <b> Login with CI </b> <h2>
    <form action="<?=base_url();?>login/proseslogin" method="post">
    <table border="0" align="center">
    <tr>
    <td> Username</td>
    <td> <input name="username" type="text"> </td>
    </tr>
    <tr>
    <td> Password</td>
    <td> <input name="password" type="password"> </td>
    </tr>
    <tr>
    <td> &nbsp; </td>
    <td> <input name="submit" type="submit" value="login"> </td>
    </tr>
    </table>
    </form>
    <?php if(isset($error)) echo "<b><span style=’color:red;’>$error</span></b>";
    if(isset($logout)) echo "<b><span style=’color:red;’>$logout</span></b>"; ?>
    </center>
    </body></html>[/sourcecode]
  2. Simpan dengan nama login_view.php, dalam folder system-application-views

Step 4 : Membuat Controller Pemrosesan Login + Logout

  1. Ketikkan script berikut,
    [sourcecode language=”php”]
    <?php
    class Login extends Controller {
    //constructor
    function login() {
    parent::Controller();
    $this->load->helper(‘url’);
    $this->load->helper(‘form’);
    $this->load->library(‘form_validation’);
    $this->load->library(‘session’);
    }
    //index for showing the login form
    function index() {
    $this->load->view(‘login_view’);
    }
    //this function will do the login process
    function proseslogin() {
    $username = $this->input->post(‘username’); //read the username that filled by the user
    $password = $this->input->post(‘password’); //read the password that filled by the user
    $passwordx = md5($password); //this is for change $password into MD5 form
    //the query is to matching the username+password user with username+password from database
    $q = $this->db->query("SELECT * FROM tb_user WHERE username=’$username’ AND userpass=’$passwordx’");
    if ($q->num_rows() == 1) {
    // if the query is TRUE, then save the username into session and load the welcome view
    $nama = $q->row()->username;
    $this->session->set_userdata(‘username’,$nama);
    $data[‘welcome’] = "Welcome $nama";
    $this->load->view(‘welcome_view’, $data);
    }
    else {
    // query error
    $data[‘error’]=’!! Wrong Username or Password !!’;
    $this->load->view(‘login_view’, $data);
    }
    }
    //to do logout process
    function logout() {
    $this->session->sess_destroy();
    $data[‘logout’] = ‘You have been logged out.’;
    $this->load->view(‘login_view’, $data);
    }
    }
    ?>
    [/sourcecode]
  2. Simpan dengan nama login.php dalam folder system-application-controllers
  3. Untuk keterangan dari script diatas, bisa dilihat dari script comment.

Step 5 : Membuat tampilan sukses login (view)

  1. Ketikkan script berikut,
    [sourcecode language=”php”]
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html><head>
    <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
    <title>Login with CI</title>
    <center>
    <?php if(isset($welcome)) echo "<h2><span style=’color:red;’>$welcome</span></h2>";
    echo "<br/>";
    echo anchor("login/logout", ‘Logout’) ?>
    </center>
    </body></html>
    [/sourcecode]
  2. Simpan dengan nama welcome_view.php dalam folder system-application-views

Step 6 : Testing Code

  1. Buka browser, pergi ke http://localhost/namaFolderCIkamu/login
  2. Akan muncul tampilan seperti dibawah,
  3. Masukkan username+password yang benar, yaitu yang ada didatabase (username : june, password : june)
  4. Maka anda akan diarahkan menuju halaman sukses login,yaitu halaman welcome seperti dibawah,
  5. Klik logout untuk keluar dari halaman welcome.
  6. Sekarang masukkan username+password salah (misal username : admin, password : admin)
  7. Maka akan ditampilkan warning seperti gambar dibawah.

Okay, Happy Coding πŸ™‚