Archive | Web Framework RSS feed for this section

Nilai Struktur Data dan WebFramework Genap 2011/2012

9 Jul

Berikut nilai untuk MK Struktur Data Kelas A dan B, dan MK WebFramework.

Jika ada pertanyaan tentang nilai silahkan melalui ocal_sophan@yahoo.com dengan mencantumkan nama, nrp, MK, kelas, pertanyaan, maksimal Rabu 11 Juli 2012.

struktur data A

struktur data B – UAS

web framework

Advertisements

Code Igniter – Export Query Result ke CSV

4 Jun

Pendahuluan

CSV adalah salah bentuk file text yang digunakan untuk menyimpan data dalam struktur tabel. Data yang tersimpan dalam CSV disimpan dalam tiap baris, dan dalam tiap baris, setiap kolom dipisahkan dengan karakter pemisah / delimiter. Karakter pemisah bisa dalam bentuk:

  • Koma ( , )
  • Titik koma ( ; )
  • Karakter tabulasi

File CSV ini bisa di buka dan di edit oleh file notepad atau excel.

Berikut adalah contoh untuk melakukan export data ke CSV.

Alur

  1. Panggil Controller untuk melakukan export ( vendor / export)
  2. Fungsi Vendor -> export
    1. Open Query
    2. Memanggil Library / Fungsi untuk export ke CSV

Tampilan Awal

Berikut contoh tampilan awal aplikasi

Controller Vendor, fungsi export

Pada baris pertama digunakan untuk menjalankan Query. Hasilnya adalah Query Result. Pada baris ke2, memanggil fungsi untuk export ke CSV. Dalam contoh ini, fungsi Export ke CSV di letakkan di dalam sebuah Library.

Fungsi to_Excel

function to_excel($query, $filename=’exceloutput’)

{

$headers = ”; // just creating the var for field headers to append to below

$data = ”; // just creating the var for field data to append to below

if ($query->num_rows() == 0)

{

echo ‘<p>The table appears to have no data.</p>’;

}

else

{

foreach ($query->list_fields() as $field)

{

$headers .= $field . “\t”;

}

foreach ($query->result() as $row)

{

$line = ”;

foreach($row as $value)

{

if ((!isset($value)) OR ($value == “”))

{

$value = “\t”;

} else

{

$value = str_replace(‘”‘, ‘””‘, $value);

$value = ‘”‘ . $value . ‘”‘ . “\t”;

}

$line .= $value;

}

$data .= trim($line).”\n”;

}

$data = str_replace(“\r”,””,$data);

header(“Content-type: application/x-msdownload”);

header(“Content-Disposition: attachment; filename=$filename.xls”);

echo “$headers\n$data”;

}

}

Tugas Kuliah Senin 4Jun’12

  • Implementasikan Export ke CSV untuk 1 tabel
  • Target Project Minimal : Desain Database Siap, tampilan Interface + menu Selesai
  • Demo : Rabu 6 Juni 2011, di Lab, jam 10:00

WebFramework: CodeIgniter – Pagination Class

14 May

CodeIgniter – Pagination class

Pendahuluan

Digunakan untuk memunculkan Link halaman ketika kita menampilkan isi dari sebuah table.

Contoh :

Library yang di pakai : pagination

Parameter yang di set:

  • Base URL
  • Jumlah baris keseluruhan / jumlah semua baris dalam tabel
  • Jumlah baris per halaman

Contoh Form

Pada form tersebut, menggunakan MVC, dengan

  • Controller pengguna, dengan fungsi yang berkaitan
    • Construct, fungsi yang selalu di jalankan ketika class di panggil
    public function __construct(){

    parent::__construct();

    $this->load->model(‘m_pengguna’);

    $this->load->library(‘table’);

    $this->load->helper(‘url’);

    $this->load->helper(‘form’);

    $this->load->library(‘pagination’);

    }

    • Index, digunakan untuk menampilkan data di list
      ada paramater page yang digunakan untuk menentukan halaman yang di panggil oleh user
Public function index($page=”){

if ($page == ”)

{

$page = ‘0’;

}

$hasil = $this->m_pengguna->tampil_semua_data(”,$page);

$this->table->set_heading(‘No’, ‘User Name’, ‘Password’, ‘Name Lengkap’,’Level’,’Actions’);

$tmpl = array( ‘table_open’ => ‘<table border=”1″ cellpadding=”4″ cellspacing=”0″>’,

‘row_alt_start’ => ‘<tr bgcolor=”#FFFF00″>’,

‘row_alt_end’ => ‘</tr>’ );

$this->table->set_template($tmpl);

$i=$page;

foreach ($hasil->result() as $row)

{

$this->table->add_row(++$i, $row->uname, ”, $row->namalengkap,
$row->id_level, anchor(‘pengguna/delete/’.
$row->uname,’hapus’,array(‘class’=> ‘delete’,
‘onclick’ =>”return confirm(‘Anda yakin akan menghapus data “.
$row->uname.”?’)”)).’.’.anchor(‘pengguna/update/’.$row->uname,’edit’));

}

//paging

$config[‘base_url’] = base_url().’index.php/pengguna/index/’;

$config[‘total_rows’] = $this->m_pengguna->recordcount();

$config[‘per_page’] = 10;

$this->pagination->initialize($config);

$data[‘isi’] = $data[‘isi’].$this->pagination->create_links();

$data[‘isi’] = $data[‘isi’].$f;

//———- Load view

$this->load->view(‘/templates/header’);

$this->load->view(‘/templates/isi’,$data);

$this->load->view(‘/templates/footer’);

}

  • Model yang digunakan adalah m_pengguna, memiliki fungsi yang terkait
    • Construct, fungsi yang selalu di jalankan ketika class di panggil
    • tampil_semua_data, digunakan untuk menampilkan semua data, dengan parameter filter nama dan nohalaman. Filter nama merupakan contoh parameter tambahan
    • recordcount

Tugas untuk didemokan Selasa 15 Mei 2012, jam9:30 di Lab

  1. Database Project telah di implementasikan
  2. 1 tabel telah diisi minimal 30 record
  3. Data di tabel tsb di tampilkan menggunakan pagination.

Jika ada pertanyaan : ocal_sophan@yahoo.com

webFramework Senin 7 mei 2012

7 May

sesuai dengan project akhir kelompok
1. design database
2. implementasikan database
3. desain interface aplikasi beserta menu
4. buat 1 form input
didemokan ke dosen, rabu 9 mei 2012,
jam 09.30, di Lab SI

jika ada pertanyaan, silahkan di sampaikan ke ocal_sophan@yahoo.com

Instalasi CodeIgniter + MVC

15 Mar

Code Igniter (CI) adalah salah satu dari webframework yang bisa digunakan dalam mengembangkan sebuah aplikasi web. CI menerapkan konsep MVC, dan cukup mudah dipelajari, sehingga banyak developer yang memanfaatkan framework ini. Dengan mencoba fitur dan library yang ada, saya yakin seorang programmer php / web developer akan sudah menguasai tool ini dalam kurang dari 24 jam belajar.

Langkah

  1. Download http://codeigniter.com/downloads/
  2. Copykan ke Folder aplikasi

Security

  1. Ubah Folder khusus CI. Folder khususnya adalah:
    1. System, misal di ubah menjadi r_system
    2. Application, misalnya di ubah menjadi r_application
  2. Buka file index.php
  3. Cari variabel:
    1. $system_folder , ubah isinya menjadi r_system
    2. $application_folder, ubah isinya menjadi r_application
  4. Metode lain, folder system dan application di letakkan di atas folder root / web root, sehingga tidak bisa di akses melalui http / browser.

Database Configuration

  • The config file is located at application/config/database.php.
$db[‘default’][‘hostname’] = “localhost”;
$db[‘default’][‘username’] = “root”;
$db[‘default’][‘password’] = “”;
$db[‘default’][‘database’] = “database_name”;
$db[‘default’][‘dbdriver’] = “mysql”;
$db[‘default’][‘dbprefix’] = “”;
$db[‘default’][‘pconnect’] = TRUE;
$db[‘default’][‘db_debug’] = FALSE;
$db[‘default’][‘cache_on’] = FALSE;
$db[‘default’][‘cachedir’] = “”;
$db[‘default’][‘char_set’] = “utf8”;
$db[‘default’][‘dbcollat’] = “utf8_general_ci”;
$db[‘default’][‘swap_pre’] = “”;
$db[‘default’][‘autoinit’] = TRUE;
$db[‘default’][‘stricton’] = FALSE;

MVC

CodeIgniter is based on the Model-View-Controller development pattern. MVC is a software approach that separates application logic from presentation. In practice, it permits your web pages to contain minimal scripting since the presentation is separate from the PHP scripting.

  • The Model represents your data structures. Typically your model classes will contain functions that help you retrieve, insert, and update information in your database.
    • Models are the place where you retrieve, insert, and update information in your database or other data stores. They represent your data.
  • The View is the information that is being presented to a user. A View will normally be a web page, but in CodeIgniter, a view can also be a page fragment like a header or footer. It can also be an RSS page, or any other type of “page”.
  • The Controller serves as an intermediary between the Model, the View, and any other resources needed to process the HTTP request and generate a web page.

CodeIgniter has a fairly loose approach to MVC since Models are not required. If you don’t need the added separation, or find that maintaining models requires more complexity than you want, you can ignore them and build your application minimally using Controllers and Views. CodeIgniter also enables you to incorporate your own existing scripts, or even develop core libraries for the system, enabling you to work in a way that makes the most sense to you.

Application Flowchart

The following graphic illustrates how data flows throughout the system:


  1. The index.php serves as the front controller, initializing the base resources needed to run CodeIgniter.
  2. The Router examines the HTTP request to determine what should be done with it.
  3. If a cache file exists, it is sent directly to the browser, bypassing the normal system execution.
  4. Security. Before the application controller is loaded, the HTTP request and any user submitted data is filtered for security.
  5. The Controller loads the model, core libraries, helpers, and any other resources needed to process the specific request.
  6. The finalized View is rendered then sent to the web browser to be seen. If caching is enabled, the view is cached first so that on subsequent requests it can be served.

CodeIgniter URLs

The segments in the URL, in following with the Model-View-Controller approach, usually represent:

example.com/class/function/ID

  1. The first segment represents the controller class that should be invoked.
  2. The second segment represents the class function, or method, that should be called.
  3. The third, and any additional segments, represent the ID and any variables that will be passed to the controller.

Controller – Contoh halaman static dengan Controller

File ini di letakkan di folder controller. Nama file hars sama dengan nama class yang akan dibuat.

File ini dipanggil dengan cara : index.php/[nama controller]/[nama methode]/[argumen]

  1. Buat di application/controllers/pages.php
  2. Isi nya
<?php

class pages extends CI_Controller {

public function view($page = ‘home’)

{

Echo “hi there”;

}

}

  1. Buka : http://192.168.56.102/ci/index.php/pages/view

Contoh lain:

<?php

class pages extends CI_Controller

{

public function view($page = ‘home’)

{

echo “memanggil halaman $page”;

}

}

?>

Dipanggil dengan : http://192.168.56.102/ci/index.php/pages/view/admin

  • Methode default yang dipanggil adalah : index, jadi jika methode tidak disebutkan, yang akan di jalankan adalah’index’
  • The controller is what will become the center of every request to your web application.
  • In very technical CodeIgniter discussions, it may be referred to as the super object

View

  • Disimpan di folder application/views
  • Contoh, kita akan membuat template halaman, yang terdiri dari header, dan footer
  • application/views/templates/header.php, isi
<html>

<head>

<title><?php echo $title ?> – CodeIgniter 2 Tutorial</title>

</head>

<body>

<h1>CodeIgniter 2 Tutorial</h1>

  • application/views/templates/footer.php
<strong>&copy; 2011</strong>

</body>

</html>

  • Controller Logic
public function view($page = ‘home’)

{


    if ( ! file_exists(‘application/views/pages/’.$page.’.php’))

    {

        // Whoops, we don’t have a page for that!

        show_404();

    }


    $data[‘title’] = ucfirst($page); // Capitalize the first letter


    $this->load->view(‘templates/header’, $data);

    $this->load->view(‘pages/’.$page, $data);

    $this->load->view(‘templates/footer’, $data);

}

  • Di application/views/pagess/contoh.php
<?php

echo “ini halaman contoh <br>”;

?>

  • The controller is now functioning! Point your browser to [your-site-url]index.php/pages/view to see your page. When you visit index.php/pages/view/about you’ll see the about page, again including the header and footer.

Dynamic Content – Model

  • Instead of writing database operations right in the controller, queries should be placed in a model, so they can easily be reused later.
  • Models are the place where you retrieve, insert, and update information in your database or other data stores. They represent your data.
  • Tabel contoh :
CREATE TABLE news ( 
    id int(11) NOT NULL AUTO_INCREMENT, 
    title varchar(128) NOT NULL, 
    slug varchar(128) NOT NULL, 
    text text NOT NULL, 
    PRIMARY KEY (id), 
    KEY slug (slug) 
);
  • Buat file : application/models/news_model.php
<?php

class news_model extends CI_Model {

public function __construct()

{

$this->load->database();

}

public function get_news($slug = FALSE)

{

if ($slug === FALSE)

{

$query = $this->db->get(‘news’);

return $query->result_array();

}
$query = $this->db->get_where(‘news’, array(‘slug’ => $slug));

return $query->row_array();

}

}

?>

Menampilkan News

  • Buat file di application/controllers/news.php
<?php

class news extends CI_Controller {

public function __construct()

{

parent::__construct();

$this->load->model(‘news_model’);

}

    public function index() 
{ 
    $data['news'] = $this->news_model->get_news(); 
    $data['title'] = 'News archive'; 
    $this->load->view('templates/header', $data); 
    $this->load->view('news/index', $data); 
    $this->load->view('templates/footer'); 
} 
    public function view($slug) 
    { 
        $data['news'] = $this->news_model->get_news($slug); 
    } 

}

?>

  • You now need to create a view to render the news items. Create application/views/news/index.php
<?php foreach ($news as $news_item): ?>

<h2><?php echo $news_item[‘title’] ?></h2>

<div id=”main”>

<?php echo $news_item[‘text’] ?>

</div>

<p><a href=”news/<?php echo $news_item[‘slug’] ?>”>View article</a></p>

<?php endforeach ?>

  • add some code to the controller and create a new view
public function view($slug) 
{ 
    $data['news_item'] = $this->news_model->get_news($slug); 
    if (empty($data['news_item'])) 
    { 
        show_404(); 
    } 
    $data['title'] = $data['news_item']['title']; 
    $this->load->view('templates/header', $data); 
    $this->load->view('news/view', $data); 
    $this->load->view('templates/footer'); 
} 
  • The only things left to do is create the corresponding view at application/views/news/view.php
<?php 
echo '<h2>'.$news_item['title'].'</h2>'; 
echo $news_item['text']; 

Create Form

  • To input data into the database you need to create a form where you can input the information to be stored. This means you’ll be needing a form with two fields, one for the title and one for the text. You’ll derive the slug from our title in the model.
  • Create the new view at application/views/news/create.php
<h2>Create a news item</h2>

<?php echo validation_errors(); ?>

<?php echo form_open(‘news/create’) ?>

<label for=”title”>Title</label>

<input type=”input” name=”title” /><br />

<label for=”text”>Text</label>

<textarea name=”text”></textarea><br />

<input type=”submit” name=”submit” value=”Create news item” />

</form>

  • form_open() function, is provided by the form helper and renders the form element and adds extra functionality, like adding a hidden CSFR prevention field.
  • validation_errors() function, is used to report errors related to form validation.
  • news controller
public function create() 
{ 
    $this->load->helper('form'); 
    $this->load->library('form_validation'); 
     
    $data['title'] = 'Create a news item'; 
     
    $this->form_validation->set_rules('title', 'Title', 'required'); 
    $this->form_validation->set_rules('text', 'text', 'required'); 
     
    if ($this->form_validation->run() === FALSE) 
    { 
        $this->load->view('templates/header', $data);     
        $this->load->view('news/create'); 
        $this->load->view('templates/footer'); 
         
    } 
    else 
    { 
        $this->news_model->set_news(); 
        $this->load->view('news/success'); 
    } 
} 
  • you can see a condition that checks whether the form validation ran successfully. If it did not, the form is displayed, if it was submitted and passed all the rules, the model is called. After this, a view is loaded to display a success message.
  • Create a view at application/view/news/success.php
  • Open up the model created earlier and add the following
public function set_news() 
{ 
    $this->load->helper('url'); 
     
    $slug = url_title($this->input->post('title'), 'dash', TRUE); 
     
    $data = array( 
        'title' => $this->input->post('title'), 
        'slug' => $slug, 
        'text' => $this->input->post('text') 
    ); 
     
    return $this->db->insert('news', $data); 
} 
  • The third line contains a new function, url_title(). This function – provided by the URL helper – strips down the string you pass it, replacing all spaces by dashes (-) and makes sure everything is in lowercase characters. This leaves you with a nice slug, perfect for creating URIs.

Controller dengan tidak memakai konsep MVC

public function lihat()

{

$this->load->database();

$query = $this->db->query(‘select * from news’);
if ($query->num_rows() > 0)

{

foreach ($query->result() as $row)

{

echo $row->title.” *** “.$row->slug.” *** HH *** “.$row->text.”<br>”;

}

}

}

PHP Dasar

Koneksi ke Tabel

<?php

$cnn = mysql_connect(“localhost”,”root”,”dvo”) or die(“Could not connect to db”);

if ($cnn) mysql_select_db(“arsip01”);

?>

$sql = “select id_bagian, nm_bagian from bagian order by id_bagian”;

$hasil = mysql_query($sql) or die(“SQL error- $sql”);

if ($hasil==false) exit;

$no1 = 1;

while ($row=mysql_fetch_row($hasil))

{

Echo $row[0].”-“. $row[1];

}

Melakukan input data ke tabel

$sql = “query”

$hasil = mysql_query($sql) or die(“”);