Categories
PHP

Melewatkan Variable antar Halaman PHP dengan URL dan Session

Studi Kasus : Melewatkan variable antar halaman dalam PHP dengan PHP Session.
Kebutuhan : Webserver Package, already installed.

Untuk kasus kali ini, asumsikan bahwa anda akan membuat aplikasi login dimana untuk halaman – halaman berikutnya setelah user tersebut login, anda ingin terus menyapa user tersebut. Tentu saja, anda harus menyimpan variable nama dari user tersebut kan? Pada dasarnya, terdapat empat cara untuk melakukan hal ini, yaitu :
1. Melewatkan variable dalam URL.
2. Melalui Session.
3. Via Cookie dan,
4. Dengan HTML Form.

Tutorial kali ini akan membahas mengenai point ke satu dan dua dari empat cara diatas, yaitu melewatkan variable melalui gabungan dari URL dan Session.

1. Ketikkan script dibawah ini (namai script1.php).

[sourcecode language=”php”]
<?php
session_start();
$_SESSION[‘username’] = "June";
?>
<html>
<head>
<TITLE>Just A Sample – ITX.WEB.ID</TITLE>
</head>
<body>
<?php
$mybook = "My Name is June";
echo "<a href=’mybook.php?book=$mybook’>";
echo "Click here to see your book!";
echo "</a>";
?>
</body>
</html>
[/sourcecode]

Perhatikan bahwa dalam script diatas, variable username kita assign secara manual (asumsi : bahwa user telah login dan username telah disimpan dalam session). Jadi, cara untuk menyimpan value dalam session adalah dengan syntax berikut :
$_SESSION['username'] = "June";

Sedangkan, variable book akan dilewatkan melalui URL. Syntax nya adalah sebagai berikut :
mybook.php?book=$mybook, dengan variable mybook telah diassign sebelumnya.

Setelah dijalankan, script diatas akan memberikan output sebagai berikut :
Click here to see your book!

2. Ketikkan script berikut (simpan dengan nama mybook.php). Script berikut adalah script dari link output script 1 diatas. Script ini yang akan membaca variable yang telah dilewat melalui URL dan Session.

[sourcecode language=”php”]
<?php
session_start();
echo "<h2> Welcome to your Book, ";
echo $_SESSION[‘username’];
echo "! </h2> <br>";
echo "Your favorite book is ";
echo $_REQUEST[‘book’];
echo "<br>";
?>
[/sourcecode]

Perhatikan bagian diatas. Dari script1.php, kita tahu bahwa kita telah melewatkan 2 buah variable, yaitu variable book dan variable username, dengan masing – masing value nya adalah My Name is June untuk variable book, dan June untuk variable username.
Maka cara membaca kedua variable tersebut adalah :
1. Membaca variable book (yang dilewatkan via URL) : $_REQUEST['book'].
2. Membaca variable username (yang dilewatkan via Session) : $_SESSION['username'].

Klik link yang dihasilkan script1.php, maka anda akan diarahkan ke halaman script 2 (mybook.php), dengan tampilan seperti gambar dibawah ini.

Haaaapy Coding πŸ˜€

Categories
PHP

Create Thumbnail Version from Image with PHP

Case Study : Create Thumbnail Version from Image with PHP GD Library
Requirements : Webserver Packages, already installed. And make sure your PHP support Image GD Library (version 1-8 above)
Follow this step..

Step 1 : Prepare the Work Folder

  1. Create folder named tutorphp in your document root
  2. Prepare sample JPG image in this folder. For this tutorial, i use this sample image (p.s. : you can use any jpeg image). If you want to use this image, just right click and save as
  3. Rename the image to myPic.jpg (p.s. : this “rename” things just to make easy for follow the tutorial πŸ˜› )

Step 2 : Create main script to resize image in to thumbnail

  1. Type the following script,
    [sourcecode language=”php”]
    <?php
    $image = ‘myPic.jpg’; //default image, change here if you want to use another image

    //get the image size and image info
    list($width_orig, $height_orig, $image_type) = getimagesize($image);

    if($image_type !== 2) { // 2 is for JPEG Image
    echo ‘Image is not JPEG Image!’;
    }
    else {
    $thumbname = ‘thumbnail_’.$image; //default name for thumbnail version of image

    // setting the height for the width 75px (75px is default width for the thumbnail). this is for maintain the ratio
    $height_tb = (int) ((75 / $width_orig) * $height_orig);

    //Create a new true color image
    $image_p = imagecreatetruecolor(75, $height_tb);

    //Create a new JPEG image from file or URL
    $image = imageCreateFromJpeg($image); //

    //Copy and resize part of an image with resampling
    imagecopyresampled($image_p, $image, 0, 0, 0, 0, 75, $height_tb, $width_orig, $height_orig);

    //upload image to folder
    if(!is_writeable(dirname($thumbname)))
    {
    echo ‘Unable to Upload image to ‘ . dirname($thumbname);
    }
    else
    {
    //output image to browser or file, the parameter is imageJPEG(resource image, name of the image, quality)
    imageJpeg($image_p, $thumbname, 100);
    }
    }
    ?>
    <center><h1>Create Thumbnail Image</h1>
    <table border=’1′ cellpadding=’5′ cellspacing=’5′>
    <tr align=’center’> <td>Original</td> <td>Thumbnail</td> </tr>
    <tr> <td><img src="myPic.jpg" alt="image" /></td> <td><img src="<?php echo $thumbname;?>" alt="thumbnail" /></td></tr>
    </table>
    <center>
    [/sourcecode]

  2. Save with the name imagetb.php, save in the tutorphp folder
  3. Explanation : see on the script (script with green) color, Okay

Step 3 : Testing Code

  1. Go to http://localhost/tutorphp/imagetb.php
  2. You can see your image (original) with its thumbnail πŸ˜€ just like the picture below..
  3. Check tutor.php folder. You will see the thumbnail_myPic.jpg file, that is thumbnail version of your image πŸ˜€

πŸ˜€

Categories
PHP

GuestBook Sederhana dengan PHP & Mysql

Studi Kasus : Membuat guestbook sederhana dengan PHP Mysql
Kebutuhan : Webserver Packages, already installed.

Ok, langsung praktik saja.

Step 1 : Persiapkan Database

  1. Buat database dengan nama db_tutorial
  2. Siapkan tabel dengan nama tb_guestbook, dengan struktur tabel seperti gambar dibawah ini.
  3. Done!

Step 2 : Persiapkan Folder Kerja

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

Step 3 : Membuat script koneksi ke Database

  1. Ketikkan script berikut,
    [sourcecode language=”php”]
    <?php
    $host = "localhost";
    $user = "root";//adjust according to your mysql setting
    $pass = ""; //adjust according to your mysql setting, i use no password here
    $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

Step 4 : Membuat form guestbook

  1. Ketikkan script berikut,
    [sourcecode language=”php”]
    <h1>Guestbook</h1>
    <form method="post" action="savegb.php">
    <table>
    <tr><td>Your Name</td><td></td></tr>
    <tr><td>Your Email</td><td></td></tr>
    <tr><td>Your Comment</td><td><textarea name="comment"></textarea></td></tr>
    <tr><td></td><td></td></tr>
    </table>
    </form>

    [/sourcecode]

  2. simpan dengan nama formguestbook.php

Step 5 : Membuat script pemrosesan dan menampilkan guestbook

  1. Ketikkan script berikut,
    [sourcecode language=”php”]
    <?php
    include ‘connect.php’;

    $name = $_POST[‘name’]; //get the name value from form
    $email = $_POST[‘email’]; //get the email value from form
    $comment = $_POST[‘comment’]; //get the comment value from form

    //query to save to database
    $q1 = "INSERT into tb_guestbook value (”,’$name’,’$email’,’$comment’)";
    $result1 = mysql_query($q1);

    //query to get data from database
    $q2 = ‘SELECT * FROM tb_guestbook order by id desc’;
    $result2 = mysql_query($q2);

    //show the data from database
    while ($record = mysql_fetch_array($result2)) {
    echo "<table>";
    echo "<tr><td>Name</td><td>:</td><td>".$record[‘name’]."</td></tr>";
    echo "<tr><td>Email</td><td>:</td><td>".$record[‘email’]."</td></tr>";
    echo "<tr><td>Comment</td><td>:</td><td>".$record[‘comment’]."</td></tr>";
    echo "</table>";
    echo "<br/>";
    }
    ?>
    [/sourcecode]

  2. simpan dengan nama savegb.php
  3. untuk penjelasan script, lihat komentar pada script πŸ˜€

Step 6 : Testing Code

  1. Pergi ke http://localhost/tutorphp/formguestbook.php. Anda akan melihat form seperti dibawah. Isikan guestbook tersebut (misal seperti pada gambar dibawah)
  2. Klik tombol save dan anda akan melihat hasilnya

OK. Haaaaaaaapppy Coding! πŸ˜€

Categories
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..

Categories
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..

Categories
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 πŸ™‚

Categories
PHP

Create a Pagination in CodeIgniter

Case Study : Create a pagination in CodeIgniter
Requirements : Webserver Package, already installed. CodeIgniter bundle.

If you aren’t familiar with the term “pagination”, pagination refers to the link which is for navigation from one page to another.just like the picture below,

Pagination will be quite easy in CI, this tutorial will give the example how to make a pagination in CodeIgniter’s application.

Okay then, prepare for a cup of tea πŸ™‚

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
    <?php
    class Buku_con extends Controller {
    public function Buku_con()
    {
    parent::__construct();
    $this->load->model('buku_model');
    $this->load->library('pagination'); //call pagination library
    }
    function getBuku() {
    //count the total rows of tb_book
    $this->db->select('*');
    $this->db->from('tb_book');
    $getData = $this->db->get('');
    $a = $getData->num_rows();
    $config['base_url'] = base_url().'index.php/Buku_con/getBuku/'; //set the base url for pagination
    $config['total_rows'] = $a; //total rows
    $config['per_page'] = '2'; //the number of per page for pagination
    $config['uri_segment'] = 3; //see from base_url. 3 for this case
    $config['full_tag_open'] = '<p>';
    $config['full_tag_close'] = '</p>';
    $this->pagination->initialize($config); //initialize pagination
    $data['title'] = 'menampilkan isi buku';
    $data['detail'] = $this->buku_model->getBuku($config['per_page'],$this->uri->segment(3));
    $this->load->view('buku_view', $data);
    }
    }
    ?>
  2. Save with the name buku_con.php in the system-application-controllers folder
  3. Explanation : function getBuku() will get the content of tb_book via model. In this controller, pagination initialized and coordinated like in the script above (see the script’s comment).

Step 4 : Create the Model

  1. Type the following script,
    <?php
    class Buku_model extends Model {
    function Buku_model()
    {
    parent::Model();
    }
    function getBuku($perPage,$uri) { //to get all data in tb_book
    $this->db->select('*');
    $this->db->from('tb_book');
    $this->db->order_by('id','DESC');
    $getData = $this->db->get('', $perPage, $uri);
    if($getData->num_rows() > 0)
    return $getData->result_array();
    else
    return null;
    }
    }
    ?>
  2. Save with the name buku_model.php in the system-application-models folder

Step 5 : Create the View

  1. Type the following script,

    <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 } ?>
    <div> <?php echo $this->pagination->create_links(); ?> </div>
  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 : Testing Code

  1. Go to http://localhost/namaFolderCIKamu/buku_con/getBuku
  2. You will see something like this,
  3. Click in the pagination link in to page 2, and you will see,


So easy, right? Just try it, and happy coding πŸ™‚

Categories
PHP

Simple Mobile Programming with PHP and DeviceAtlas

Case Study : Create simple mobile site with PHP and Device Atlas Device Database
Requirements : Webserver Package, already installed. DeviceAtlas Database, download here. Maybe you should register first before able to download it. Be calm, it’s free.

Brief Overview
In this tutorial, we will focus on detecting what device that used by the user to access our mobile site. You may see something like “Download game for your Nokia 6610” or “Free theme for your K610i

How could your handphone could detected? This called Device Recognition.

We can do it, Device Recognition with API that provided by Device Atlas.

Okay Then, let us try.

Step 1 : DeviceAtlas Installation and Prepare for Working Folder

  1. Create a folder named helloMobile on your document root.
  2. Unzip device atlas that you’ve been download in to document root, so the structure folder is as shown below,

    DA Extract
  3. Copy json folder from sample folder, paste in helloMobile folder
  4. End of the working folder structure is as shown below,

    Folder Structure

Step 2 : Work with PHP

  1. Type the following script,
    <?php
    //file name : index.php
    //author : littleflow3r
    //Include API
    require_once 'Mobi/Mtld/DA/Api.php';
    $tree = Mobi_Mtld_DA_Api::getTreeFromFile('json/Sample.json');
    $ua = $_SERVER['HTTP_USER_AGENT'];
    $logo = 'logo.png';
    header ("Cache-Control: max-age=200 ");
    header ("Content-Type: application/xhtml+xml ");
    echo '<?xml version="1.0" encoding="utf-8"?>';
    ?>
    <!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.2//EN"
    "http://www.openmobilealliance.org/tech/DTD/xhtml-mobile12.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head>
    <title>My First Mobile</title>
    <link rel="stylesheet" href="style.css" type="text/css"/>
    </head>
    <body>
    <img id="logo" src="<?php echo $logo;?>" alt="logo"/>
    <?php
    try {
    $isbro = Mobi_Mtld_DA_Api::getPropertyAsBoolean($tree, $ua, 'isBrowser');
    } catch (Mobi_Mtld_Da_Exception_InvalidPropertyException $e) {
    $isbro = "Not a Desktop Browser";
    }
    try{
    $vendor = Mobi_Mtld_DA_Api::getProperty($tree, $ua, 'vendor');
    } catch (Mobi_Mtld_Da_Exception_InvalidPropertyException $e) {
    $vendor = "Unknown Vendor";
    }
    try{
    $model = Mobi_Mtld_DA_Api::getProperty($tree, $ua, 'model');
    } catch (Mobi_Mtld_Da_Exception_InvalidPropertyException $e) {
    $model = "Unknown Model";
    }
    ?>
    <h1><?php if ($isbro=='1') echo 'You"re Using Desktop';
    else { echo 'You"re Using '.$vendor.' '.$model;} ?></h1>
    </body>
    </html>
  2. Save with the name index.php in helloMobile folder
  3. Explanation:
    require_once 'Mobi/Mtld/DA/Api.php';
    $tree = Mobi_Mtld_DA_Api::getTreeFromFile('json/DeviceAtlas.json');
    $ua = $_SERVER[β€˜HTTP_USER_AGENT’];

    The code above is a code to initialize DA Api, with including API Class and provide path from JSON Database.

    While the following code is used for device recognition,

    [01] $ua = $_SERVER['HTTP_USER_AGENT'];
    [02] $model = Mobi_Mtld_DA_Api::getProperty($tree, $ua, 'model');
    [03] $isbro = Mobi_Mtld_DA_Api::getPropertyAsBoolean($tree, $ua, 'isBrowser');
    [04] $ismobile = Mobi_Mtld_DA_Api::getPropertyAsBoolean($tree, $ua, 'mobileDevice');
    [05] $display = Mobi_Mtld_DA_Api::getPropertyAsInteger($tree, $ua, 'displayWidth');
    [06] $vendor = Mobi_Mtld_DA_Api::getPropertyAsString($tree, $ua, 'vendor');

    Code [02]
    because it is not defined (untyped) so $model will produce device characteristics with String type. Model show the model from the used device. (ex : 6600, iPhone, N96).
    Code [03] define the type as boolean, so it will produce boolean value (0 or 1). For example, characteristics with the name isBrowser, for identifying whether device is a desktop browser (1 if True, 0 if False).
    Code [04]
    $ismobile will return boolean value, indicated whether the device is recognized mobile device or mobile browser.
    Code [05]
    $display will return the device’s display width on the integer value.
    Code [06]
    $vendor will return string value from the device’s vendor.

    <?php if ($isbro=='1') echo 'You"re Using Desktop';
    else { echo 'You"re Using '.$vendor.' '.$model;} ?>

    The Code above will show β€œYou’re using Desktop” confirmation if isBrowser value is 1, and other than that the system will display the information in accordance with the vendor and model / type of device you use.

Step 3 : Testing Code

  1. Go to http://localhost/helloMobile
  2. You will se an image like below,
    Result in Desktop
  3. If you access it via handphone, ex. IPhone, You will see image like below,

    Result in Iphone
  4. Or access it via Nokia,

    Result in Nokia 7250
  5. Or Blackberry πŸ˜€ ,
    Result in BlackBerry
Categories
PHP

Mendapatkan Feed Situs lain Via RSS Reader SimplePie

Studi Kasus : Mendapatkan Feed situs lain dengan RSS Reader SimplePie, menampilkannya, dan menyimpannya ke dalam database.
Kebutuhan : SimplePie library, download here. Webserver Packages, already installed.

RSS (Really Simple Syndication) adalah format berbasis XML yang digunakan untuk sharing dan delivering konten dari web yang pada umumnya diupdate secara regular. Sedangkan istilah ‘feed‘ mengacu pada output dari RSS yang dapat dibaca dengan RSS Feed Reader (pembaca rss feed). SimplePie merupakan RSS Feed Reader/Parser yang cukup terkenal (dan paling saya sukai tentunya), cara kerja dari RSS Feed Parser semacam ini adalah dengan membaca format XML yang terdapat dalam RSS Feed yang kita tentukan sendiri.

Ok, langsung praktik saja.

Step 1 : Persiapkan Database

  1. Buat database dengan nama db_tutorial
  2. Siapkan tabel dengan nama tb_rss, dengan struktur tabel seperti gambar dibawah ini.
    Table Structure
  3. Done with the database!

Step 2 : Persiapkan Folder Kerja

  1. Buat folder baru di document root anda dengan nama folder rss
  2. Buat sebuah folder didalam folder rss dengan nama cache (…/rss/cache)
  3. Copy file SimplePie.inc (hasil download – yang berada dalam file ZIP simplePie) ke dalam folder rss.

Step 3 : Membuat Koneksi ke database

  1. Buat script untuk melakukan koneksi ke database, yaitu dengan ketikkan script dibawah ini,
    <?php
    //file name : connect.php
    //author : littleflow3r
    $host = "localhost";
    $user = "root"; //sesuaikan dengan setting mysql
    $pass = ""; //
    sesuaikan dengan setting mysql
    $dbName = "db_tutorial";
    mysql_connect($host, $user, $pass);
    mysql_select_db($dbName)
    or die ("Connect Failed !! : ".mysql_error());
    ?>
  2. Simpan dalam folder rss dengan nama connect.php

Step 4 : Inisialisasi SimplePie

  1. Ketikkan script dibawah ini,
    <?php
    //file name : initRSS.php
    //author : littleflow3r
    require_once 'simplepie.inc';
    //initialize simplePie
    $feed = new SimplePie('http://localhost/websmsmasking/feed/rss');
    $feed->set_cache_location('../rss/cache/');
    $feed->set_feed_url('http://localhost/websmsmasking/feed/rss');
    $feed->init();
    $feed->handle_content_type();
    ?>
  2. Simpan dalam folder rss dengan nama initRSS.php
  3. Keterangan : Cara kerja dari SimplePie RSS Parser adalah dengan membaca format XML yang terdapat dalam RSS Feed. Code diatas digunakan untuk menginisialisasi SimplePie, dengan memasukkan alamat dari rss kita [baris 06 dan baris 08]. Sebagai contoh, saya memakai sample alamat rss adalah localhost/websmsmasking/feed/rss –> feed dari aplikasi lokal saya. Anda bisa mengganti alamat ini dengan alamat rssfeed yang anda inginkan, namun untuk mendapatkan feed dari situs online, anda juga harus menjalankan program secara online (terhubung ke internet, karena simplepie akan mengakses alamat dari feed tersebut secara langsung.)

Step 5 : Menampilkan Feed

  1. Ketikkan script berikut,
    <?php
    //file name : rss.php
    //author : littleflow3r
    include 'initRSS.php';
    include 'connect.php';
    //get the feed and show it
    echo "<h1> RSS News Update </h1>";
    foreach ($feed->get_items(0,4) as $item):
    $permalink = $item->get_permalink();
    $title = $item->get_title();
    $desc = $item->get_description();
    echo '<a href="'.$permalink.' ">'; echo $title; echo '</a>';
    echo "<br>";
    echo $desc;
    echo "<br>"; echo "<br>";
    //insert to database
    $q = "INSERT into tb_rss (link, title, description) VALUES('$permalink','$title','$desc')";
    $result = mysql_query($q);
    endforeach;
    ?>
  2. Simpan dalam folder rss dengan nama rss.php
  3. Keterangan : Baris 08 menunjukkan looping dengan foreach sejumlah feed yang didapat dari alamat RSS yang telah ditentukan, dengan menggunakan fungsi get_items(0,4), maksudnya adalah mengambil 4 Feed items dimulai dari record ke 0.
    Baris 09 adalah menyimpan permalink dari setiap items yang didapat dalam variabel $permalink
    Baris 10 adalah mendapatkan judul feed dengan fungsi get_title kemudian disimpan dalam $title.
    Baris 11 adalah mendapatkan deskripsi dari feed dengan fungsi get_desc kemudian disimpan dalam $desc.

Step 6 : Testing Code

  1. Buka browser, jalankan http://localhost/rss/rss.php
  2. Anda akan melihat feed dari alamat rss yang anda masukkan tadi telah tertampil seperti gambar dibawah,
    Result
  3. Cek database anda, lihat bahwa tb_rss telah terisi dengan content rss dari alamat feed anda.
    Tb_RSS

Okay, Done. Happy Trying! Happy Coding πŸ™‚

Categories
PHP

The Use of Date/Time Function in PHP

Case Study : Using the the Date/Time Function in PHP
Requirements : Webserver Package (XAMPP, EasyPHP, APPServ), already installed.

If you developing PHP application, the date function is one of the function that will used most often. The simple example is, we will use this function to count some people’s age from her/his birth.

Here are some examples of the use of the date / time function that is often used in develop applications with php.

1. Showing Current Date in various formats

Asumption : Today is Thursday, 25 November 2010

  • Format : 2010-11-25
    The code is : date("Y-m-d");
  • Format : November 25, 2010, 8:17 PM
    Code : date("F j, Y, g:i a");

For more details about the output format of date, see the following table (click on the table to see table more clearly):

Output Date Format

2. Calculating Range/Date differences

Script:

<?php
function datediff($tgl1, $tgl2){
$tgl1 = strtotime($tgl1);
$tgl2 = strtotime($tgl2);
$diff_secs = abs($tgl1 - $tgl2);
$base_year = min(date("Y", $tgl1), date("Y", $tgl2));
$diff = mktime(0, 0, $diff_secs, 1, 1, $base_year);
return array( "years" => date("Y", $diff) - $base_year, "months_total" => (date("Y", $diff) - $base_year) * 12 + date("n", $diff) - 1, "months" => date("n", $diff) - 1, "days_total" => floor($diff_secs / (3600 * 24)), "days" => date("j", $diff) - 1, "hours_total" => floor($diff_secs / 3600), "hours" => date("G", $diff), "minutes_total" => floor($diff_secs / 60), "minutes" => (int) date("i", $diff), "seconds_total" => $diff_secs, "seconds" => (int) date("s", $diff) );
}
$tgl1 = '1989-06-06';
$tgl2 = date("Y/m/d/ h:m:s");
$a = datediff($tgl1, $tgl2);
echo 'tanggal 1 = '.$tgl1; echo '<br>';
echo 'tanggal 2 = '.$tgl2; echo '<br>';
echo 'Selisih = '.$a[years].' tahun '.$a[months].' bulan '.$a[days].' hari '.$a[hours].' jam '.$a[minutes].' menit '.$a[seconds].' detik';
?>

This script will produce output like the example image below:

Difference Between 2 Date
3. Date Adding

In the script below we will try to add days, months, and years at current date so as to produce output in the form of a certain date results of the addition.

Code :

<?php
$todayDate = date("Y-m-d");// current date
echo "Today: ".$todayDate."<br>";
$now = strtotime(date("Y-m-d"));
//Add one day to today
$date = date('Y-m-j', strtotime('+1 day', $now));
echo "After adding 1 day = ".$date."<br>";
$addMonth = 5;
//Add variabel addMonth to today
$date2 = date('Y-m-j', strtotime('+'.$addMonth.' month', $now));
echo "After adding $addMonth month = ".$date2."<br>";
//Add 6 year to today
$date3 = date('Y-m-j', strtotime('+6 year', $now));
echo "After adding 6 year = ".$date3."<br>";
?>

Output dari script diatas adalah seperti tertampil pada gambar dibawah :

Date Adding

4. Knowing Whether Today is the Last Day of the Month

Script :

<?php
// If today is the last day of the month, do echo
if(date('j') == date('t')) {
echo 'Today is the Last Day of this month';
}
else echo 'Today is NOT the Last Day of this month';
?>

Output :

Last Date ?

5. Calculating remaining days in this year

Script :

<?php
$today = getdate();
$yday = ($today['yday']);
$leap = date('L');
$tdl = $leap + 365;
$dliy = $tdl - $yday;
echo "Dari hari ini ".date('Y-m-d ').", Kita masih memiliki sisa " . $dliy . " hari dalam tahun ini.";
?>

Output :

Day Remain in Year

Hope that several examples from the use of date function above will be useful for all. I myself often use it, of course.

Okay, Happy Coding πŸ™‚