web application development with php

49
Develop Web Application Using PHP & mySql Written by : Agus Suhartono Pelatihan Pengembangan Aplikasi Berbasis Web LP3I Semarang i

Upload: agus-suhartono

Post on 08-Jul-2015

324 views

Category:

Technology


2 download

DESCRIPTION

Buku kecil bagaimana belajar membuat aplikasi web dengan PHP

TRANSCRIPT

Page 1: Web application development with PHP

Develop Web ApplicationUsing PHP & mySql

Written by : Agus Suhartono

Pelatihan Pengembangan Aplikasi Berbasis WebLP3I Semarang

i

Page 2: Web application development with PHP

1. PETA JALAN ................................................................................................................. 1

1.1. HUBUNGAN WEB APPLICATION DAN DESKTOP APPLICATION ............................................... 1 1.2. TEKNOLOGI YANG BERHUBUNGAN .................................................................................... 2 1.3. 3 LEVEL PENGEMBANGAN .............................................................................................. 3 1.4. MENGUPLOAD KE WEB-SERVER ...................................................................................... 3

2. PENGENALAN BAHASA PHP ................................................................................... 4

2.1. MENGENAL HTML ...................................................................................................... 4 2.2. SEJARAH PHP .............................................................................................................. 5 2.3. PHP DAN HTML ........................................................................................................ 6 2.4. KOMENTAR PROGRAM .................................................................................................... 7 2.5. PENULISAN PROGRAM .................................................................................................... 7

3. TIPE DATA .................................................................................................................... 8

3.1. JENIS TIPE DATA .......................................................................................................... 8 3.2. TIPE DATA STRING ........................................................................................................ 8

Latihah 3.2 ............................................................................................................... 8

4. VARIABLE DAN KONSTANTA .............................................................................. 10

4.1. DEFINISI ..................................................................................................................... 10 4.2. PENAMAAN VARIABLE .................................................................................................. 10 4.3. REFERENSI VARIABEL .................................................................................................. 11 4.4. KONSTANTA ............................................................................................................... 11

Latihan 4.4 ............................................................................................................. 12

5. OPERATOR ................................................................................................................. 13

5.1. OPERATOR ARITMATIKA ............................................................................................... 13 5.2. OPERATOR PENETAPAN (ASSIGNMENT) ........................................................................... 13 5.3. OPERATOR LOGIKA ...................................................................................................... 13 5.4. OPERATOR PERBANDINGAN ........................................................................................... 13 5.5. OPERATOR PENGGABUNGAN STRING (CONCATENATION OPERATOR) .................................... 14

Latihan 5.5 ............................................................................................................. 14 5.6. OPERATORS INCREMENT/DECREMENT ........................................................................... 14

Latihan 5.6 ............................................................................................................. 14 5.7. OPERATOR PERUBAH TIPE DATA (CAST OPERATOR) ........................................................ 15

7. STRUKTUR PERCABANGAN ................................................................................. 16

7.1. STRUKTUR PERCABANGAN IF ......................................................................................... 16 7.1.1. Struktur Percabangan if Tungal ...................................................................... 16 7.1.2. Struktur Percabangan if else ........................................................................... 16 7.1.3. Struktur Percabangan if elseif ......................................................................... 16

Latihan 7.1 ............................................................................................................. 17 7.2. STRUKTUR PERCABANGAN SWITCH. ................................................................................ 18

Latihan 7.2 ............................................................................................................. 19

8. STRUKTUR PERULANGAN .................................................................................... 20

ii

Page 3: Web application development with PHP

8.1. PERNYATAAN WHILE. ................................................................................................... 20 8.2. PERNYATAAN DO…WHILE ............................................................................................. 21 8.3. PERNYATAAN FOR ........................................................................................................ 22 8.4. FOREACH .................................................................................................................... 23 8.5. BREAK ........................................................................................................................ 23 8.6. CONTINUE .................................................................................................................. 23

9. FUNGSI ........................................................................................................................ 25

9.1. USER-DEFINED FUNCTIONS ........................................................................................... 25 9.2. FUNCTION SCOPE ........................................................................................................ 25

9.2.1. Tanpa variable global ..................................................................................... 25 9.2.2. Menggunakan variabel $GLOBAL[] ............................................................... 26 9.2.3. Menggunakan keyword global ........................................................................ 26

9.3. MENGEMBALIKAN NILAI ............................................................................................... 26 9.4. PARAMETER BERDASAR NILAI ....................................................................................... 27 9.5. PARAMETER BERDASAR REFERENSI ................................................................................ 27 9.6. PARAMETER DEFAULT .................................................................................................. 27 9.7. VARIABLE STATATIS .................................................................................................... 28

10. MODULARISASI ...................................................................................................... 30

10.1. REQUIRE() ................................................................................................................ 30 Latihan 10.1 ............................................................................................................... 30 File : latihan10-1a.html ............................................................................................. 30 File : latiham10-1-header.php .................................................................................. 30 File : latihan10-1-footer.php ..................................................................................... 31 File : latihan10-1-utama.php .................................................................................... 31

10.2. INCLUDE() ................................................................................................................ 31 10.3. REQUIRED_ONCE() DAN INCLUDE_ONCE() ...................................................................... 32

11. BEKERJA DENGAN ARRAY ................................................................................. 34

11.1. DEKLARASI ARRAY ................................................................................................... 34 11.1.1. Assignment dengan Nomor Array ................................................................. 34 11.1.2. Assignment dengan Nomor Array Tidak Disebut .......................................... 34 11.1.3. Deklarasi dengan array() .............................................................................. 34

11.2. ARRAY ASOSIATIF ..................................................................................................... 34 11.2.1. Deklarasi langsung ........................................................................................ 34 11.2.2. Deklarasi dengan array() .............................................................................. 34

11.3. MENGAMBIL DATA ARRAY DENGAN FOREACH .............................................................. 35

12. MEMBUAT WEB FORM ......................................................................................... 36

12.1. TAG <FORM></FORM> .............................................................................................. 36

12.2. TEKS FIELD <INPUT TYPE="TEXT" … > ..................................................... 36

Fungsi : ..................................................................................................................... 36 Bentuk ........................................................................................................................ 36 Contoh : ..................................................................................................................... 36

12.3. TEXTAREA ............................................................................................................... 36

iii

Page 4: Web application development with PHP

Fungsi : ...................................................................................................................... 36 Bentuk : ...................................................................................................................... 37

12.4. CHECKBOX .............................................................................................................. 37 Fungsi: ...................................................................................................................... 37 Bentuk ........................................................................................................................ 37

12.5. RADIO BUTTON ......................................................................................................... 37 Fungsi : ...................................................................................................................... 37 Bentuk : ..................................................................................................................... 37

12.6. LIST BOX ................................................................................................................. 37 Fungsi : ...................................................................................................................... 37 Bentuk ....................................................................................................................... 37

12.7. CONTOH ................................................................................................................... 37

13. MANAGEMEN SESI ................................................................................................ 40

13.1. COOKIE .................................................................................................................... 40 13.2. PHP SESSION ........................................................................................................... 41

13.2.1. Mengawali Sebuah Sesi dengan session_start() ............................................ 41 13.2.2. Menyimpan/Menetapkan Variable Session. .................................................. 42 13.2.3. Mengambil Variable Session. ........................................................................ 42 13.2.4. Menghapus Variable Session. ....................................................................... 42 13.2.5. Menghentikan Session. .................................................................................. 42

14. OBJECT ORIENTED PROGRAMMING .............................................................. 43

14.1. PENDAHULUAN .......................................................................................................... 43 14.2. CLASS SEBAGAI CETAK BIRU OBJEK. .......................................................................... 43 14.3. MENCIPTAKAN OBJECT .............................................................................................. 44 14.4. MENGAKASES PROPERTI DAN METODE ......................................................................... 44

iv

Page 5: Web application development with PHP

Database Server

Web Server : Web Application

Desktop Application/Client

Web Browser/Client

1. Peta Jalan

1.1. Hubungan Web Application dan Desktop Application

Kelebihan dan Kekurangan :

1. Tidak perlu didistribusikan di setiap klien (klien hanya butuh browser)

2. Tidak membutuhkan resource besar di komputer klien, proses bisnis dilakukan di server

3. Membutuhkan bandwidth network lebih besar dibanding aplikasi dektop, karena user interface juga di transfer.

4. Lebih sulit dibuat, karena membutuhkan beberapa keahlian: server scripting, HTML, CSS (optional), JavaScript (optional), dll.

1. Aplikasi perlu didistribusikan di setiap klien

2. Membutuhkan resource besar di komputer klien, karena proses bisnis dilakukan di klien (untuk multi tier, proses bisnis utama bisa dipisah)

3. membutuhkan bandwidth network lebih ringan karena hanya data yang diperlukan saja yang dikirim (jika menggunakan database server, tetapi jika menggunakan database berbasis file - seperti MS Access – tidak)

4. Lebih mudah dibuat karena membutuhkan lebih sedikit kemampuan.

1

Page 6: Web application development with PHP

1.2. Teknologi yang Berhubungan

DATABASE

mySql

MS SQL

ORACLE

PostgreSQL

WEB SERVER

PHP

Perl

ASP/ASP.Net

JSP

C/C++

Pascal/Delphi

Basic/VB/VB.Net

CLIENT /WEB BROWSER

FireFox

MS Internet Explorer

Netscape Nav

Mozilla

HTML

WML

CSS

JavaScript

WAP Browser

XUL

DOJO Widget

2

Page 7: Web application development with PHP

1.3. 3 Level Pengembangan

1. Core Level : Membuat aplikasi dengan menggunakan fasilitas PHP murni tanpa menggunakan 3th Party Library

2. Library Level : Membuat aplikasi dengan menggunakan fasilitas PHP dan 3th Party Library secara independen, misalnya :

a. ADODB, database layerb. Smarty, template engine (presentation layer)c. PhpSecureSite, managemen user/logind. JpGraph, graphic librarye. EzPDF, membuat file PDFf. phpMailer, mengirim emailg. domit, XML Parser

3. Framework Level : Membuat aplikasi dengan menggunakan framework yang ada, library sudah tercakup di dalamnya: Contoh

a. FuseBox (PHP4, OOP)b. PostNuke (PHP4, prosedural)c. Xaraya (PHP4, prosedural)d. Prado, (PHP5, berbasis komponent, OOP)e. WACT (PHP4, OOP)

1.4. Mengupload ke Web-Server

Berbeda dengan file HTML yang bisa dijalankan tanpa web browser, dokumen PHP harus diupload ke Web-Server untuk bisa dijalankan.

Kita bisa menggunakan Explorer, FTP Client, Web Manager, tergantung system yang digunakan.

PHP LanguangeCore

ADODB Smarty phpSecureSite JpGraph

EzPDF phpMailer domit

Library

FuseBox Xaraya Prado WACTFramework

3

Page 8: Web application development with PHP

2. Pengenalan Bahasa PHP

2.1. Mengenal HTML

HTML: hyper text markup languange

Format umum :

<html><head>

<title>…</title>......

</head>

<body>......

</body></html>

<h1>…</h1> Heading 1<h2>…</h2> Heading 2<h3>…</h3> Heading 3<p>…</p> Paragraph<br>, <br /> Ganti Baris<hr> Garis Horisontal<code>…</code> Format code<b>...</b> Bold / huruf tebal<u>…</u> Underline / huruf dengan garis bawah<i>…</i> Italic / huruf miring

Note : File html desimpan dengan ekstensi .html atau .htm

4

Page 9: Web application development with PHP

Latihan 2.1 :

<html><head><title>Welcome: Dunia HTML</title></head>

<body><h1>Dunia HyperText Markup Language</h1><p>HTML merupakan bahasa pemformatan dokumen yang bersifat global, maksudnya: multi browser, multi operating system.</p>

<h2>HTML dan PHP</h2><p>HTML dan PHP bisa menjadi satu-kesatuan dalam dokumen yang sama, ini sungguh menyenangkan.</p></body></html>

Simpan dengan nama latihan_2-1.html

Hasil :

2.2. Sejarah PHP1995 versi 1 dibuat oleh Rasmus Lerdof1996 versi 2 PHP/F11997 versi 3 dibuat oleh banyak orang2000 versi 4 diintegrasikan dengan Zend Engine(Zeev Suraski)???? versi 5 penyempurnaan OOP

5

Page 10: Web application development with PHP

2.3. PHP dan HTMLSeperti ASP, PHP ditulis dengan disisipkan di dalam dokumen HTML. Untuk menyisipkan, script PHP harus diletakkan diantara tag berikut:

<? Perintah ditulis di sini?>

<?php perintah ditulis di sini?>

Setiap baris perintah harus diakhiri dengan tanda titik koma (;)Setiap file yang berisi script PHP harus disimpan dengan ekstensi .php

Latihan 2.3 :

<html><head><title>Welcome: Dunia HTML</title></head>

<body><? echo “<h1>Contoh Pertama Script PHP</h1>”;?><p>HTML merupakan bahasa pemformatan dokumen yang bersifat global, maksudnya: multi browser, multi operating system.Didalam dokumen HTML bisa disisipi </p>

<h2>HTML dan PHP</h2><p>HTML dan PHP bisa menjadi satu-kesatuan dalam dokumen yang sama, ini sungguh menyenangkan.</p></body></html>

Simpan dengan nama latihan_2-3.php .

6

Page 11: Web application development with PHP

2.4. Komentar Program

C style : diapit /* …*/C++ style : diawali // (hanya untuk 1 baris)Shell style : diawali # (hanya untuk 1 baris)

2.5. Penulisan Program

nama variable : huruf kecil dan huruf besar dibedakannama fungsi : huruf besar dan huruf kecil tidak dibedakan

7

Page 12: Web application development with PHP

3. Tipe Data3.1. Jenis Tipe DataAda 5 tipe data :

• Integer (Long on C)• Floating Point (Double on C)• String• Array• Object

Bab ini hanya akan membahas tipe string, integer dan floating point cukup jelas, sedangkan Array dan Object akan dibahas dalam bab tersendiri.

3.2. Tipe Data StringTipe data string ditulis dengan diapit oleh karakter ‘…’ (petik tunggal) atau “…” (petik ganda). Kelebihan untuk petik ganda adalah, variable dapat langsung diambil nilainya jika variable tersebut ditaruh didalamnya.

Latihah 3.2

<html><head>

<title>Tipe data String </title></head>

<body><?$nama = “Unnes”;echo “nilai $nama”;echo “nilai \$nama = $nama”;echo ‘nilai $nama = ’ . $nama;?></body></html>

Simpan dengan nama latihan_3-2.php

8

Page 13: Web application development with PHP

Escaped character

Kode Arti\n Baris baru\r Carriege\t Tab horisontal\\ Backslash\$ Tanda dollar\” Tanda kutip/petik\regex Sesuai konsep Regular Expresion

9

Page 14: Web application development with PHP

4. Variable dan Konstanta4.1. DefinisiVariable digunakan untuk menyimpan nilai, dimana nilai tersebut bisa diubah ketika program berjalan.

4.2. Penamaan Variable• Diawali karakter dollar $, mis $username.• Karakter yang diijinkan: huruf, anggka garis bawah.• Karakter pertama bisa huruf atau garis bawah• Huruf kecil dan besar dibedakan

Latihan 4.2 :

<html><head><title>Variable</title></head>

<body>Contoh penggunaan variable <br><?$presiden = "Soekarno";echo "Presden RI I : $presiden";echo "<br>";

$presiden = "Soeharto";echo "Presden RI II : $presiden";echo "<br>";

$presiden = "Gus Dur";echo "Presden RI III : $presiden";echo "<br>";

$presiden = "Mbak Mega";echo "Presden RI IV : $presiden";echo "<br>";

$presiden = "Suslilo Bambang Yudoyono";echo "Presden RI V : $presiden";

?></body></html>

Simpan file dengan nama latihan_4-2.php.

10

Page 15: Web application development with PHP

4.3. Referensi VariabelReferensi sebuah variable dapat disimpan dalam variable lain, sehingga yang disimpan bukan nilainya, melainkan alamatnya di memori. Cara mengambil referensi adalah dengan menambahkan karakter & di depan variable yang diambil.

Latihan 4.3 :

<html><head><title>Referensi Variable</title></head>

<body>Contoh penggunaan referensi variable <br><?$presiden = "Soekarno";$presidenX = &$presiden;

echo "Presden RI I $presidenX ";echo "<br>";

$presiden = "Soeharto";echo "Presden RI II $presidenX ";echo "<br>";

$presiden = "Gus Dur";echo "Presden RI III $presidenX ";echo "<br>";

$presiden = "Mbak Mega";echo "Presden RI IV $presidenX ";echo "<br>";

$presiden = "Suslilo Bambang Yudoyono";echo "Presden RI V $presidenX ";

?></body></html>

Simpan file dengan nama latihan_4-3.php.

4.4. Konstanta

Konstanta digunakan untuk menyimpan nilai yang tetap selama aplikasi berjalan.Konstanta dideklarasikan dengan fungsi define() sebagai berikut :

define( “nama-konstanta”, nilai) ;

11

Page 16: Web application development with PHP

Latihan 4.4

<html><head><title>Konstanta</title></head><body><h1>Contoh Konstanta</h1><?php

define("phi", 3.14);

$r = 5;$luas = phi * pow($r,2);echo "PHI : " . phi;echo "<br>";echo "Jari-jari : " . $r;echo "<br>";echo "Luas lingkaran : $luas";?></body></html>

Simpan dengan nama latihan_4-4.php

12

Page 17: Web application development with PHP

5. OperatorOperator digunakan untuk melakukan sebuah operasi pada satu atau lebih nilai.

5.1. Operator Aritmatika

+ Penambahan- Pengurangan* Pembagian/ Perkalian% Modulus

5.2. Operator Penetapan (Assignment)

Assignmen adalah operasi pemberian nilai (kepada variable).

= $a = nilai += $b += a ekivalen dengan $b = $b + a-= $b -= a ekivalen dengan $b = $b - a*= $b -= a ekivalen dengan $b = $b - a/= $b -= a ekivalen dengan $b = $b / a

5.3. Operator Logika

Operator Operasi&& ,and And

||, or Orxor Xor! Not

5.4. Operator Perbandingan

Operator Operasi== Sama dengan=== Identik (sama dengan & sama tipe)!= Tidak sama dengan!== Lawan dari ===< Kurang dari> Lebih dari<= Kurang dari atau sama dengan>= Lebih dari atau sama dengan

13

Page 18: Web application development with PHP

5.5. Operator Penggabungan String (Concatenation Operator)Untuk menggabungkan dua buah string atau lebih digunakan karakter . (titik).

Latihan 5.5

<html><head><title>Concatenation Operator </title></head>

<body><?php

echo " teknik " . " sipil " . " unnes ";echo "<br>";

// atau $a = " teknik ";$b = " sipil ";$c = " unnes ";$d = $a . $b . $c; echo $d;?></body></html>

5.6. Operators Increment/Decrement Operator increment dan decrement digunakan untuk menambah dan mengurangi suatu nilai.

Operator Name Effect on $var Value of the Expression

$var++ Post-increment

$var is incremented by 1.

The previous value of $var.

++$var Pre-increment $var is incremented by 1.

The new value of $var (incremented by 1).

$var-- Post-decrement

$var is decremented by 1.

The previous value of $var.

--$var Pre-decrement

$var is decremented by 1.

The new value of $var (decremented by 1).

Latihan 5.6

<html><head><title> Increment/Decrement Operators </title></head>

14

Page 19: Web application development with PHP

<body><?php echo "Pre Increment";$num1 = 5;$num2 = ++$num1; echo "<br>";echo $num1; echo "<br>";echo $num2; echo "<br>";

$num1 = 5;$num2 = $num1++; echo "Post Increment";echo "<br>";echo $num1; echo "<br>";echo $num2; echo "<br>"; ?>

</body></html>

5.7. Operator Perubah Tipe Data (Cast Operator)

Digunakan untuk merubah tipe data suatu variable

Operator Changes Type To

(int), (integer) Integer

(float), (real), (double) Floating point

(string) String

(bool), (boolean) Boolean

(array) Array

(object) Object

Contoh :

$str = "5";$num = (int) $str;

15

Page 20: Web application development with PHP

7. Struktur Percabangan

7.1. Struktur Percabangan if

7.1.1. Struktur Percabangan if TungalFormat :

if (ekspresi) {Pernyaaan1Pernyaaan2…PernyaaanN

}

if (ekspresi)Pernyaaan ;

7.1.2. Struktur Percabangan if elseFormat :

if (ekspresi) {Pernyaaan1Pernyaaan2…

} else {Pernyaaan5Pernyaaan6…

}

7.1.3. Struktur Percabangan if elseifFormat :

if (ekspresi) {Pernyaaan1Pernyaaan2…

} elseif {Pernyaaan5Pernyaaan6…

}

16

Page 21: Web application development with PHP

Latihan 7.1

<html><head><title>if.... </title></head>

<body>

<?php

$var = 60;

echo "<h2>if tunggal</h2>";

if ($var >= 50) { echo '1. $var is in range '; echo '2. $var is in range ';}

echo "<br>";

if ($var >= 50) echo '3. $var is in range';

echo "<h2>if else</h2>";

echo "<br>";

if ($var >= 50) { echo '4. $var is in range';} else { echo '5. $var is invalid';}

echo "<br>";

$num=5;

echo "<h2>if elseif</h2>";

if ($num < 0) { echo '6. $num is negative';} elseif ($num == 0) { echo '7. $num is zero';} elseif ($num > 0) { echo '8. $num is positive';}

echo "<br>";

if ($num < 0) { echo '9. $num is negative';} elseif ($num == 0) { echo '10. $num is zero';

17

Page 22: Web application development with PHP

} else { echo '11. $num is positive';}

?>

</body></html>

7.2. Struktur Percabangan switch.

Format :

switch (expr){ case expr: statement list case expr: statement list ... default: statement list}

18

Page 23: Web application development with PHP

Latihan 7.2

<html><head><title>switch...</title></head><body><?php

$jawaban = "Y";switch ($jawaban) { case 'y': case 'Y': print "Jawaban : YA"; break; case 't': case 'T': case 'n': case 'N': print "Jawaban : TIDAK"; break; default: print "Error: Jawaban tidak sah"; break;}

?></body></html>

19

Page 24: Web application development with PHP

8. Struktur Perulangan

8.1. Pernyataan while.Format

while (ekspresi) {pernyataan….

}

do statementwhile (expr);

20

Page 25: Web application development with PHP

Latihan 8.1

<html><head><title>while</title></head><body><?php

$n=10;$m=$n;$result = 1;

while ($n > 0) { $result *= $n--;

$i = $m - $n;echo "Hasil ke $i : $result";

echo "<br>";}

?>

</body></html>

8.2. Pernyataan do…while

Format :

do statement

21

Page 26: Web application development with PHP

while (expr);

8.3. Pernyataan for

Format :

for (start_expressions; truth_expressions; increment_expressions) {

pernyataan…

}

Latihan 8.3.o<html><head>

<title>for...</title></head><body><?php

for ($i = 0; $i < 10; $i++) { print "Pangkat 2 dari $i adalah : " . $i*$i . "<br>\n";}?></body></html>

22

Page 27: Web application development with PHP

8.4. foreach

Format :

Foreach (array_exp as $value) {PERNYATAAN……….

}Latihan 8.4

<html><head>

<title>foreach...</title></head><body><?php

$a = array (1,2,3,14);foreach ($a as $v) { echo “$v<br>”;}?></body></html>

8.5. breakDigunakan untuk menghentikan iterasi pada loops

Format :break [ekspresi];

8.6. ContinueDigunakan untuk meloncati loop/kembali dari awal.

Format :continue [ekspresi];

23

Page 28: Web application development with PHP

24

Page 29: Web application development with PHP

9. Fungsi

Format umum :

func(arg1,arg2,...)

Contoh :

$length = strlen("UNNES");

9.1. User-Defined Functions

Format :

function function_name (arg1, arg2, arg3, ...){ statement list}

Latihan 9.1

<?php

function square ($x){ return $x*$x;}

echo 'The square of 5 is ' . square(5);

?>

9.2. Function Scope

9.2.1. Tanpa variable global

Latihan 9.2.1

<?php

function func (){ $var = 2;}

$var = 1;

25

Page 30: Web application development with PHP

func();echo $var;

?>

9.2.2. Menggunakan variabel $GLOBAL[]

Bentuk

$GLOBALS["nama_var"] = $nilai;

Latihan 9.2.2

<?phpfunction func (){ $GLOBALS["var"] = 2;}

$var = 1;func();echo $var;

?>

9.2.3. Menggunakan keyword global

Format :

global $var1, $var2, ...;

Latihan 9.2.3

<?php

function func(){ global $var; $var = 2;}

$var = 1;func();echo $var;

?>

9.3. Mengembalikan Nilai

Format return <nilai>;

26

Page 31: Web application development with PHP

9.4. Parameter Berdasar Nilai

Latihan 9.4

<?php

function kali( $x, $y) {$hasil = $x * $y ;

return $hasil;}

$nilai = kali(4,5);echo “$nilai”;

?>

9.5. Parameter Berdasar Referensi

Latihan 9.5

<?php

function increment(&$num, $increment){ $num += $increment;}

$num = 4;increment($num, 1);echo “$num<br>”;increment($num, 3);echo “$num<br>”;

?>

9.6. Parameter Default

Latihan 9.6

<?php

function increment(&$num, $increment = 1){ $num += $increment;}

27

Page 32: Web application development with PHP

$num = 4;increment($num);echo “$num<br>”;increment($num, 3);echo “$num<br>”;

?>

9.7. Variable Statatis

Format :static nama_variable = nilai_awal;

Latihan 9.7

<?php

function cetak_terus (){ $first_time = true; $pencacah = 1;

if (first_time) {echo “cetak terus ya? <br>”;echo “pencacah : $pencacah <br>”;

}

$first_time = false; $pencacah++ ;

}

function cetak_sekali(){ static $first_time = true; static $pencacah = 1;

if ($first_time) {echo “cetak sekali aja ya? <br>”;echo “pencacah : $pencacah <br>”;

}

$first_time = false; $pencacah++ ;

}

cetak_terus();cetak_sekali();

28

Page 33: Web application development with PHP

cetak_terus();cetak_sekali();

cetak_terus();cetak_sekali();

cetak_terus();cetak_sekali();

?>

29

Page 34: Web application development with PHP

10. Modularisasi

Yang dimaksud modularisasi adalah, pembagian program-program menjadi beberapa file sesuai dengan fungsionalitasnya.

10.1. require()require() adalah bentuk konstruksi yang digunakan untuk menggabungkan suatu script PHP atau text dari file lain dengan script PHP yang memanggilnya. Script atau file yang digabungkan tidak harus berisi script/code program PHP. Jika script atau file yang digabungkan berupa script maka PHP akan mengevaluasi dan mengeksekusinya.

Latihan 10.1

File : latihan10-1a.html

<html><head><title>Sim Informasi Akademi</title></head><body>

<h1>Sim Informasi Akademik</h1>

Menu : <a href="index.php">Home</a> | <a href="about.php">About</a> | <a href="about.php">Dosen</a> | <a href="about.php">Mahasiswa</a>

<hr>

<H2>Home Page</h2>

<p>Selamat datang di Sistim Informasi Akademik UNNES</p>

<hr>

Copyright &copy; LP3i

</body></html>

File : latiham10-1-header.php

<html><head><title>Sim Informasi Akademi</title></head><body>

30

Page 35: Web application development with PHP

<h1>Sim Informasi Akademik</h1>

Menu : <a href="index.php">Home</a> | <a href="about.php">About</a> | <a href="about.php">Dosen</a> | <a href="about.php">Mahasiswa</a>

<hr>

File : latihan10-1-footer.php

<hr>

Copyright &copy; Teknik Sipil UNNES

</body></html>

File : latihan10-1-utama.php

<?phprequire("latihan10-1-header.php");

?>

<H2>Home Page</h2>

<p>Selamat datang di Sistim Informasi Akademik UNNES</p>

<?php

require("latihan10-1-footer.php");

?>

10.2. include()

Berbeda dengan require(), maka include() merupakan konstruksi yang digunakan untuk menggabungkan suatu script atau file dengan script pemanggilnya.

Include() dapat dipanggil berkali-kali dalam looping.

Contoh :

$file = array(“satu.inc”, “dua.inc”, “tiga.inc”);for ($i=0; $i,3; $i++) { include($file[$i]); }

31

Page 36: Web application development with PHP

10.3. required_once() dan include_once()

required_once() dan include_once() digunakan untuk memastikan fungsi-fungsi yang ada di dalam file yang dipanggil hanya akan loading satu kali.

32

Page 37: Web application development with PHP

33

Page 38: Web application development with PHP

11. Bekerja dengan Array

Array adalah variable berindex, dimana sebuah variable bias mempunyai beberapa nilai.

11.1. Deklarasi Array

11.1.1. Assignment dengan Nomor Array

$mahasiswa[3] = “Didin”;$mahasiswa[4] = “Dudun”;$mahasiswa[0] = “Dadang”;

11.1.2. Assignment dengan Nomor Array Tidak Disebut

$mahasiswa[] = “Didin”; // 0$mahasiswa[] = “Dudun”; // 1$mahasiswa[] = “Dadang”; // 2

11.1.3. Deklarasi dengan array()

Bentuk :

$nama_var = array(nilai1, nilai2, nilai3,…);

Contoh :

$mahasiswa = array(“Didin”, “Dudun”, “Dadang”);

11.2. Array AsosiatifArray asosiatif adalah array yang tidak menggunakan nomor elemen tetapi menggunakan string.

11.2.1. Deklarasi langsung

$telfon[“Didin”] = “024111111”;$telfon[“Dudun”] = “024222222”;$telfon[“Dadang”] = “024222222”;

11.2.2. Deklarasi dengan array()$telfon = array(

“Didin” => “024111111”, “Dudun” => “024222222”, “Dadang” => “0243333333”

);

34

Page 39: Web application development with PHP

11.3. Mengambil Data Array dengan foreach

Bentuk

foreach ( $var_array as $var_value ) {

}

$mahasiswa

foreach ($var_array as $var_key => $var_value ) {

}

Contoh :

$mahasiswa[] = “Didin”;$mahasiswa[] = “Dudun”;$mahasiswa[] = “Dadang”;

foreach ($mahasiswa as $nama) { echo “Nama mahasiswa : $nama <br>”;}

<?php

$telfon[“Didin”] = “024111111”;$telfon[“Dudun”] = “024222222”;$telfon[“Dadang”] = “024222222”;

foreach ($telfon as $nama => $nomor ) { echo “Telfon mahasiswa $nama : $nomor <br>”;}

?>

35

Page 40: Web application development with PHP

12. Membuat Web Form

12.1. Tag <form></form>

Fungsi :Dipakai sebagai container komponen-komponen gui yang akan ditampilkan sebagai bagian dari form.

Bentuk :

<form daftar-atribut>

</form>

<form name="namaForm" enctype="jenis_tipe_data" method="cara-pengiriman" action="skrip-tujuan" >

enctype :application/x-www-form-urlencoded (default)multipart/form-data (untuk upload file)

12.2. Teks Field <input type="text" … >Fungsi : digunakan sebagai inputan teks berbentuk textbox

Bentuk<input name="namaField " type="text" [disabled] size="size-val" maxlength = " maxlength-val" [readonly]>

Contoh :<input name="textfield" type="text" disabled="false" size="10" maxlength="10" readonly="false" [value=””]>

12.3. TextAreaFungsi :Digunakan untuk memasukkan data teks dengan jumlah banyak dengan tampilan multi baris.

36

Page 41: Web application development with PHP

Bentuk : <textarea name="textarea" cols="10" rows="10" tabindex="0"> nilai </textarea>

12.4. CheckBoxFungsi: Memasukkan data bersifat true atau false, jadi hanya ada dua pilihan.Bentuk<input type="checkbox" name="nama-cekbox " value="nilai">

12.5. Radio ButtonFungsi :memberi pilihan kepada user dalam bentuk option buttonBentuk : <input type="radio" name="radGender" value="L">Laki-Laki

12.6. List BoxFungsi :Memberika pilihan kepada pengguna dalam bentuk kotak daftarBentuk <select name="lstPekerjaan" size="1"> <option value="0">Pengangguran</option> <option value="1">Wiraswasta</option> <option value="2">Pegawai Negri</option> </select>

Catatan : Penggunaan framework seperti PRADO lebih memudahkan dalam pembuatan webform, karena PRADO berbasis komponen.

12.7. Contoh

webform.htm

<html><head><title>Demo WebForm</title></head><h1>Form 1</h1>

<body><form name="form1" method="post" action="save.php" ><fieldset><legend> Demo WebForm </legend> <p>Nama : <input name="txtNama" type="text" size="30" maxlength="50"> <br> Password : <input name="txtPassword" type="password" size="15" maxlength="15">

37

Page 42: Web application development with PHP

<br> Jenis Kelamin :

<label><input type="radio" name="radJenisKelamin" value="L" checked> Laki-Laki </label> <label><input type="radio" name="radJenisKelamin" value="P" > Perempuan </label> <br> Hobi : <label><input type="checkbox" name="chkHobi1" value="Memancing" checked>Memancing </label> <label><input type="checkbox" name="chkHobi2" value="Membaca"> Membaca </label><br> Pekerjaan : <select name="lstPekerjaan[]" size="5" multiple> <option value="Pengangguran">Pengangguran</option> <option value="Wiraswasta">Wiraswasta</option> <option value="Pegawai Negri">Pegawai Negri</option> </select> <br> Komentar : <textarea name="txtKomentar" cols="30" rows="5" accesskey="K"> </textarea> <br> <input type="submit" name="Submit" value="Submit"> <input type="reset" name="Reset" value="Reset"> </p> </fieldset></form></body></html>

readform.php

<html><head><title>Untitled Document</title></head>

<body><?php echo "Nama : " . $_REQUEST["txtNama"]; echo "<br />";

echo "Password : " . $_REQUEST["txtPassword"];

echo "<br />";

if (isset($_REQUEST["radJenisKelamin"])) { echo "Jenis Kelamin : " . $_REQUEST["radJenisKelamin"] ; echo "<br />";

}

if (isset($_REQUEST["chkHobi1"])) { echo "Hobi 1 : " . $_REQUEST["chkHobi1"]; echo "<br />";

38

Page 43: Web application development with PHP

}

if (isset($_REQUEST["chkHobi2"])) { echo "Hobi 2 : " . $_REQUEST["chkHobi2"];

echo "<br />"; } if (isset($_REQUEST["lstPekerjaan"])) {

echo "Pekerjaan : <br />"; $i=1;

foreach ($_REQUEST["lstPekerjaan"] as $nPekerjaan) { echo "$i $nPekerjaan"; $i++;

echo "<br />"; }

echo "<br />"; } echo "Komentar : " . $_REQUEST["txtKomentar"]; // ?></body></html>

39

Page 44: Web application development with PHP

13. Managemen Sesi

Hubungan web browser dan server web bersifat stateless, artinya tidak ada hubungan koneksi yang dipelihara antara keduanya. Hal ini perlu managemen khusus untuk menjaga informasi antara klien dan server.

Ada dua cara yang bisa dilakukan :1. dengan cookie2. dengan php Session

13.1. CookieCookie digunakan untuk menyimpan informasi di klien, dimana informasi ini bisa dipanggil oleh halaman lain.

setcookie(“<namavar>”, “<nilaivar>”, <batas-waktu>);

Note: • Jika <batas-waktu> tidak ditetapkan maka cookieakan ada terus.• Jika <nilaivar> tidak ditetapkan, berarti menghapus cookie.

Untuk membaca variable cookie digunakan variable $_COOKIE[“<namavar>”]

Contoh :

cookie1.php

<?// Contoh pembuatan cookies.// cookies1.php

if(isset($_REQUEST["submit"])) {setcookie("nama" ,$_REQUEST["nama"] );setcookie("email" ,$_REQUEST["email"] );

?>

<html><head>

<title>Cookies</title></head><body>

<p align=\"center\"><b>Cookies telah diset:</b></p><p align=\"center\">Nama : <b><? echo $_REQUEST["nama"]; ?></b></

p><p align=\"center\">Email : <b><? echo $_REQUEST["email"]; ?

></b></p><p align=\"center\"><a href="cookies2.php">Halaman dua</a></p>

40

Page 45: Web application development with PHP

<? }else{ ?>

<html><head>

<title>Cookies</title></head><form method="POST" action="cookies1.php">

<p align="center">Nama : <input type="text" name="nama" size="31"></p>

<p align="center">Email : <input type="text" name="email" size="32"></p>

<p align="center"><input type="submit" value="LOGIN" name="submit"></p>

<p>&nbsp;</p></form>

<?}?></body></html>

Cookie2.php

<br><p align="center"><b>Halaman Dua:</b></p><p align="center">Nama : <b><? echo $_COOKIE["nama"]; ?></b></p><p align="center">Email : <b><? echo $_COOKIE["email"]; ?></b></p>

13.2. PHP Session13.2.1. Mengawali Sebuah Sesi dengan session_start()

Untuk memulai session maka setiap halaman yang memanfaatkan session harus diawali dengan fungsi session_start().

Setelah session_start() dijalankan maka akan terbentuk session id yang bisa diambil dari fungsi session_id() .

41

Page 46: Web application development with PHP

Contoh : session_start.php

<?php session_start(); ?><html><head><title>Menggunakan fungsi session</title></head><body>

<?echo "<br>Selamat datang di halaman session…<br>ID session Anda adalah : ". session_id();?>

<br>Selamat datang di halaman session…<br>ID session Anda adalah : <?php echo session_id(); ?>

</body></html>

13.2.2. Menyimpan/Menetapkan Variable Session.Peritah :

$_SESSION[’<nama_variable>’] = <nilai_variable> ;

13.2.3. Mengambil Variable Session.

$x = $_SESSION[’<nama_variable>’] ;

13.2.4. Menghapus Variable Session.

unset( $_SESSION['<nama_variabel>'] );

13.2.5. Menghentikan Session.Untuk menghentikan session digunakan fungsi session_destroy(). Sebelum fungsi ini dijalankan sebaiknya dijalankan dulu perintah $_SESSION = array() untuk mengosongkan variable $_SESSION.

42

Page 47: Web application development with PHP

14. Object Oriented Programming

14.1. PendahuluanKonsep OPP adalah menyatukan antara data/variabel dan fungsi/metode, data dikenal sebagai sifat/karakter sedangkan fungsi sebagai tindakan/perilaku.

Sebagai contoh objek binatang, maka dia akan mempunyai sifat : warna, suara, kecepatan berlari, dll. Sedangkan idakan yang dilakukan misalnya bersuara, berlari, makan, mencium, dll.

Pada umumnya data disebut sebagai property (property) sedangkan tindakan disebut sebagai metode (method).

14.2. Class Sebagai Cetak Biru Objek.Kelas (Class) merupaka cetak biru sebuak objek. Setiap objek dibuat berdasarkan Kelas (Class)yang ada.

Untuk mendefinisikan kelas bentuknya sebagi berikut :

class Nama-Kelas{

[ var ][ daftar fungsi/metode]

}

Contoh :

class Vegetable {

var $edible; var $color;

function Vegetable( $edible, $color="green" ) { $this->edible = $edible; $this->color = $color; }

function is_edible() { return $this->edible; }

function what_color() { return $this->color; } }

43

Page 48: Web application development with PHP

14.3. Menciptakan ObjectUntuk menciptakan objek, caranya adalah

$nama_variabel_objek = new nama_kelas;

Jika kelas mempunyai konstruktor caranya adalah :

$nama_variabel_objek = new nama_kelas(daftar-parameter);

Perhatikan bahwa sebuah objek merupakan sebuah variable.

Contoh :

$sayur = new Vegetable;$sayur = new Vegetable(true, "red");

14.4. Mengakases Properti dan MetodeUntuk mengakses property atau metode dipake perintah berikut

$var_object->property$var_object->method([parameter-list])

Contoh :

$sayur = new Vegetable(true, "red");echo "Warna sayur adalah : " . $sayur-> what_color();

44

Page 49: Web application development with PHP

45