PDO (PHP Data Objects)

PDO Introduction

PDO (PHP Data Objects) adalah salah satu ekstensi yang disupport oleh PHP5 untuk mendefinisikan lightweight DBMS connection abstraction library atau dapat juga disebut database abstraction library. PDO digunakan untuk melakukan koneksi dengan berbagai macam database yang di support oleh PHP.

Jika anda pernah menggunakan PHP dan database MySQL anda pasti pernah menggunakan perintah-perintah sebagai berikut:

mysql_connect($host, $user, $password);
mysql_select_db($db);

Atau ketika anda menggunakan PHP dan database SQL Lite maka anda menggunakan perintah:

$dbh = sqlite_open($db, 0666);

Dengan menggunakan perintah-perintah tersebut diatas maka aplikasi yang anda buat akan terikat dengan database yang anda gunakan secara spesifik. Ketika anda akan melakukan migrasi database maka anda harus merubah seluruh script anda, dan hal ini akan sangat menyulitkan anda.

PDO menawarkan cara yang berbeda untuk bekerja dengan database secara lebih umum, dengan PDO perintah yang anda tuliskan untuk koneksi dengan database MySQL, SQLite, dan Postgree adalah sebagai berikut:

// For MySQL:
$conn = new PDO("mysql:host=$host;dbname=$db", $user, $pass);
// For SQLite:
$conn = new PDO("sqlite:$db");
// And for PostgreSQL:
$conn = new PDO("pgsql:host=$host dbname=$db", $user, $pass);

Dengan PDO anda akan tidak perlu mengganti kode yang sudah anda buat sebelumnya ketika akan melakukan migrasi program.

Pada tutorial dibawah ini penulis akan menunjukan bagaimana cara bekerja dengan database menggunakan PDO.

Database Sample

Buat sample database yang akan digunakan pada aplikasi contoh, pertama buat database dengan nama pdo kemudian buat dua table dengan nama books dan authors

mysql> create database pdo;
Query OK, 1 row affected (0.05 sec)
mysql> use pdo;
Database changed
mysql> create table books(
    -> id int primary key not null auto_increment
    -> author int not null,
    -> title varchar(70) not null,
    -> isbn varchar(20),
    -> publisher varchar(30) not null,
    -> year int(4) not null,
    -> summary text(2048));
Query OK, 0 rows affected (0.17 sec)
mysql> create table authors(
    -> id int primary key not null auto_increment
    -> firstName varchar(30) not null,
    -> lastName varchar(40) not null,
    -> bio text(2048));
Query OK, 0 rows affected (0.00 sec)

Tambahkan record kedalam table author sebagai berikut:

mysql> insert into authors(firstName, lastName, bio) values(
     -> 'Marc', 'Delisle', 'Marc Delisle is a member of the MySQL
Developers Guide');
Query OK, 1 row affected (0.14 sec)
mysql> insert into authors(firstName, lastName, bio) values(
     -> 'Sohail', 'Salehi', 'In recent years, Sohail has contributed
to over 20 books, mainly in programming and computer graphics');
Query OK, 1 row affected (0.00 sec)
mysql> insert into authors(firstName, lastName, bio) values(
     -> 'Cameron', 'Cooper', 'J. Cameron Cooper has been playing
around on the web since there was not much of a web with which to
play around');
Query OK, 1 row affected (0.00 sec)

Jika anda select semua data pada table authors maka dapt dilihat recordnya sebagai berikut:

mysql> select id, firstName, lastName from authors;
+----+-----------+----------+
| id | firstName | lastName |
+----+-----------+----------+
|  1 | Marc      | Delisle  |
|  2 | Sohail    | Salehi   |
|  3 | Cameron   | Cooper   |
+----+-----------+----------+
3 rows in set (0.03 sec)

Tambahkan record pada table books sebagai berikut:

mysql> insert into books(author, title, isbn, publisher, year, 
summary) values(
     -> 1, 'Creating your MySQL Database: Practical Design Tips and
Techniques', '1904811302', 'Packt Publishing Ltd', '2006',
     -> 'A short guide for everyone on how to structure your data and
set-up your MySQL database tables efficiently and easily.');
Query OK, 1 row affected (0.00 sec)
mysql> insert into books(author, title, isbn, publisher, year, 
summary) values(
     -> 2, 'ImageMagick Tricks', '1904811868', 'Packt Publishing
Ltd', '2006',
     -> 'Unleash the power of ImageMagick with this fast, friendly
tutorial, and tips guide');
Query OK, 1 row affected (0.02 sec)
mysql> insert into books(author, title, isbn, publisher, year,
summary) values(
     -> 3, 'Building Websites with Plone', '1904811027', 'Packt
Publishing Ltd', '2004',
     -> 'An in-depth and comprehensive guide to the Plone content
management system');
Query OK, 1 row affected (0.00 sec)

Mendesain Kode

Desain arsitektur aplikasi yang baik adalah salah satu kunci membangun aplikasi selain desain data model yang benar. Pada contoh aplikasi yang akan dibuat kali ini, pertama anda harus membuat file untuk koneksi dengan database yang akan dipanggil disetiap file yang membutuhkan koneksi dengan database.

Pertama buat file dengan nama common.inc.php yang akan berisi kode untuk koneksi dengan database. Kemudian tuliskan kodenya sebagai berikut:

<?php
/**
 *File untuk koneksi 
 */
//dbconnection string dan username/password
$connStr="mysql:host=localhost;dbname=pdo";
$user="root";
$pass="";

function showHeader($title){
?>
  <html>
  <head><title><?=htmlspecialchars($title)?></title></head>
  <body>
  <h1><?=htmlspecialchars($title)?></h1>
  <a href="books.php">Books</a>
  <a href="authors.php">Authors</a>
  <hr/>
<?php 
}

function showFooter(){
?>
  </body>
  </html>
<?php    
}

//membuat connection object
$conn = new PDO($connStr,$user,$pass);
?>

Untuk menampilkan data yang ada pada table books buat file books.php, kemudian ketikan kode berikut:

<?php
include_once 'common.inc..php';

$q = $conn->query("select * from books order by title");

showHeader('Books');
?>
<table width="100%" border="1" cellpadding="3">
<tr style="font-weight: bold">
  <td>Title</td>
  <td>ISBN</td>
  <td>Publisher</td>
  <td>Year</td>
  <td>Summary</td>
</tr>
<?php
while($r=$q->fetch(PDO::FETCH_ASSOC)){
?>
  <tr>
    <td><?=htmlspecialchars($r['title'])?></td>
    <td><?=htmlspecialchars($r['isbn'])?></td>
    <td><?=htmlspecialchars($r['publisher'])?></td>
    <td><?=htmlspecialchars($r['year'])?></td>
    <td><?=htmlspecialchars($r['summary'])?></td>
  </tr>
<?php    
}
?>
</table>
<?php
    showFooter();
?>

Jika dijalankan maka tampilannya adalah sebagai berikut :

image

Untuk menampilkan data pada table author buat halaman dengan nama authors.php, kemudian ketik kodenya sebagai berikut:

<?php
include_once 'common.inc.php';
$q=$conn->query("select * from authors order by lastname,firstname");
showHeader('Authors');
?>
<table width="100%" border="1" cellpadding="3">
<tr style="font-weight: bold">
  <td>First Name</td>
  <td>Last Name</td>
  <td>Bio</td>
</tr>
<?php
    while($r=$q->fetch(PDO::FETCH_ASSOC)){
?>
    <tr>
        <td><?=htmlspecialchars($r['firstName'])?></td>
        <td><?=htmlspecialchars($r['lastName'])?></td>
        <td><?=htmlspecialchars($r['bio'])?></td>
      </tr>
<?
    }
?>
</table>
<?php
    showFooter();
?>

image

 
Menggunakan Parameter untuk menampilkan Author

Pada contoh dibawah ini akan ditunjukan bagaimana cara untuk menggunakan parameter yang dikirimkan lewat url (query string). Buat file dengan nama authordetails.php kemudian tulis kode berikut:

<?php
include_once('common.inc.php');
 
$id = $_REQUEST['id'];
$q = $conn->query("select * from authors where id=$id");
$author = $q->fetch(PDO::FETCH_ASSOC);
$q->closeCursor();
 
if(!$author){
    showHeader('Error');
    echo "Salah memasukan id author";
    showFooter();
    exit;    
}
showHeader("Author: $author[firstName] $author[lastName]");
$q = $conn->query("select * from books where author=$id order by title");
$q->setFetchMode(PDO::FETCH_ASSOC);

?>
<h2>Author</h2>
<table width="60%" border="1" cellpadding="3">
<tr>
  <td><b>First Name</b></td>
    <td><?=htmlspecialchars($author['firstName'])?></td>
</tr>
<tr>
  <td><b>Last Name</b></td>
  <td><?=htmlspecialchars($author['lastName'])?></td>
</tr>
<tr>
  <td><b>Bio</b></td>
  <td><?=htmlspecialchars($author['bio'])?></td>
</tr>
</table>

<h2>Books</h2>
<table width="100%" border="1" cellpadding="3">
<tr style="font-weight: bold">
  <td>Title</td>
  <td>ISBN</td>
  <td>Publisher</td>
  <td>Year</td>
  <td>Summary</td>
</tr>

<?php
while($r=$q->fetch()){
?>
<tr>
      <td><?=htmlspecialchars($r['title'])?></td>
      <td><?=htmlspecialchars($r['isbn'])?></td>
      <td><?=htmlspecialchars($r['publisher'])?></td>
      <td><?=htmlspecialchars($r['year'])?></td>
      <td><?=htmlspecialchars($r['summary'])?></td>
</tr>
<?php 
}
?>
</table>
<?php
showFooter();
?>

Jalankan dengan menuliskan alamat url http://localhost/authordetails.php?id=2, anda dapat melihat hasil tampilan sebagai berikut:image

Jika id yang anda masukan tidak ada misal: http://localhost/authordetails.php?id=99 maka akan muncul halaman error-nya

image

Continue reading

Calculator Postfix

#include "stdio.h"
#include "string.h"
#include "stdlib.h"

#define MAX 20

int data[20];
int top=-1;

int isFull(){
	if(top==MAX-1) return 1; else return 0;
}

int isEmpty(){
	if(top==-1) return 1; else return 0;
}

void push(int d){
	if(isFull()==0){
		top++;
		data[top]=d;
	}
}

int pop(){
	int t=-1;
	if(isEmpty()==0){
		t=data[top];
		top--;
	}
	return t;
}

void operasi(char o){
	int a, b, h;
	switch(o){
		case '+':
					a = pop();
					b = pop();
					h = b + a;
					push(h);
					break;
		case '-':
					a = pop();
					b = pop();
					h = b - a;
					push(h);
					break;
		case '*':
					a = pop();
					b = pop();
					h = b * a;
					push(h);
					break;
		case '/':
					a = pop();
					b = pop();
					h = b / a;
					push(h);
					break;
		case '=':
					a = pop();
					if(a!=-1) printf("%d\n",a);
					else printf("EMPTY\n");
	}
}

int isOp(char* op){
	if(strcmp(op,"+")==0 || strcmp(op,"-")==0 || strcmp(op,"*")==0 || strcmp(op,"/")==0 || strcmp(op,"=")==0)
		return 1;
	else return 0;
}

void main(){
	char d[10];
	while(1){
		scanf("%s",d);
		if(isOp(d)){
			operasi(d[0]);
		} else if(strcmp(d,"x")==0){
			break;
		} else push(atoi(d));
	}
}

Kelas VB.NET Database

Training VB.NET Database berlangsung pada tanggal 01 Sept – 18Sept, selama kurang lebih 24jam (6x-12x) pertemuan dengan materi:

  • Intro .NET Framework
  • Intro VB.NET
  • OOP with VB.NET
  • ADO.NET (Connection, Command, DataReader, DataSet, DataView)
  • SQL Server Strore Proc
  • Report with Cysrstal Report
  • Charting with 3rd Component
  • Setup n Deployment
  • Case Study: Inventory Control /Stock

Peserta kelas ini terdiri dari 6 orang yang kesemuanya adalah mahasiswa Teknik Informatika, Leonardus (TI UKDW), Urent (TI UKDW 04), Etha (TI UKDW 04), Ronny (TI UKDW), Benny (TI UKDW)

Pelatihan ASP.NET 3.5 (C#)

Pada tanggal 20 Agustus – 4 September 2008 diadakan pelatihan ASP.NET 3.5 (C#), total waktu 24jam, 6x pertemuan, dengan materi sebagai berikut:

  • Intro .NET 3.5 Framework
  • Server Control
  • User Control
  • Theme / Skin
  • Site Map
  • Master Page
  • SQL Server 2005 Express
  • DataSource Control
  • DataBinding (GridView, DetailsView,DataList,Repeater,FormView)
  • New ListView dan DataPager (.NET 3.5)
  • ASP.NET AJAX (Server / Client)
  • Case Study: Simple E-Commerce App

Kelas ini diikuti oleh 5 orang peserta yang semuanya adalam mahasiswa Teknik Informatika, Gusde (TI Atma 05), Andik (TI Atma 05), Alit (TI Atma 05), Wahama (TI Atma 05), Erwin Setiawan (TI UKDW 04)

Pelatihan PHP & MySQL

Pada tanggal 15-18 Agustus 2008 telah berlangsung pelatihan private intensif (8 jam/hari) dengan topik:

  • PHP5 OOP
  • PDO (PHP Data Object)
  • MySQL InnoDb
  • MySQL Stored Proc, Trigger
  • Case Study: Simple E-Commerce
  • PHP MVC (CodeIgniter)

Adapun peserta pelatihan adalah Bapak Rekso Soenaryo dari PT Krakatau Medika, Cilegon, Banten.

Training ASP.NET 3.5 di UKRIDA

Pada tanggal 1 -5 Agustus 2008, diadakan training ASP.NET 3.5 di Universitas Kristen Krida Wacana, Jakarta dengan trainer Erick Kurniawan,S.Kom, M.Kom. Peserta pelatihan adalah dosen dan programmer dari unit PTI (Pusat Teknologi Informasi) dan FTI (Fakultas Teknik Informatika) Universitas Kirsten Krida Wacana adapun materi pelatihan selama kurang lebih 5 hari adalah pengenalan teknologi ASP.NET 3.5, detail materinya adalah sebagai berikut:

  • Penggunaan Standar Control, Validation Control, dan Rich Control
  • Master Pages, Theme, User Control
  • DataSource Control: SqlDataSource Control untuk akses data
  • DataBound Control: List, GridView, DetailsView, Repeater, FormView, dan DataList
  • DataBoudn Control: ListView dan DataPager (New Feature ASP.NET 3.5)
  • Site Navigation, Site Map
  • Security: Menggunakan Login Control, CreateUserWizard, LoginName, ChaangePassword, PasswordRecovery, dan LoginView
  • ASP.NET Membership: Authentication, Authorization, ASP.NET Membership Class, Role Manager
  • LINQ to SQL: Introduction ORM, LINQ to SQL, LINQ Expression, CRUD dengan LINQ to SQL, LinqDataSource Control  (New .NET 3.5)
  • ASP.NET AJAX: Server Side ASP.NET AJAX, ASP.NET AJAX Control Toolkit, Client Side ASP.NET AJAX.

 

image

Gambar Suasana Pelatihan ASP.NET di Lab Komputer UKRIDA

 

image

Gambar Erick Kurniawan (trainer) dengan peserta training Pak Edy dari FTI UKRIDA

Kelas Baru VB.NET periode Agustus

Dibuka kelas baru VB.NET untuk periode bulan agustus, materi pelatihannya adalah:

  • Introducing Visual Basic 2005
  • .NET Framework (CLR, Managed Code, Namespaces, Types dan Object, Class Library)
  • Introduction OOP (Abstraction, Encapsulation, Interface, Polymorphism, Overloading)
  • Variables dan Data Types (Value dan Reference Types, Variable Scope, lifetime, Access level, Arrays, Collections)
  • Operators (Arithmetic operator, Comparison, Object operator, Operator overloading)
  • Generic
  • Error Handling
  • SQL Server Express 2005
  • Studi Kasus: Aplikasi Stok, Pembelian, Penjualan

Lama Training: 24 jam (jadwal diatur sesuai dengan permintaan peserta dan kesediaan trainer)

Pendaftaran: email ke actualtraining@gmail.com atau telp 08156881169

Kapasitas Peserta: 6 orang

Peserta yang sudah mendaftar saat ini sebanyak 3 orang

kelas akan segera dimulai jika jumlah peserta sudah memenuhi