Professional Documents
Culture Documents
kecil dan
PHP + MySQL PHP dikombinasikan dengan MySQL akan menghasilkan aplikasi yang crossplatform (artinya kita dapat mengembangkan aplikasi di Windows dan dijalankan di server Unix). Mengapa PHP? PHP dapat berjalan pada bermacam platforms (Windows, Linux, Unix, dll.). PHP kompatibel dengan hampir semua server web yang ada (Apache, IIS, etc.). PHP dapat di-download secara gratis dari situs resminya: http://www.php.net/ PHP mudah dipelajari dan berjalan secara efisien di server web. Bagaimana cara memulai PHP Install server Apache pada Windows atau Linux. Install PHP pada Windows atau Linux. Install MySQL pada Windows atau Linux.
Bab 4 Variabel
Variabel digunakan untuk menyimpan suatu nilai, seperti angka, string atau hasil dari suatu fungsi, sehingga dapat digunakan berulangkali pada program. Variabel di PHP Semua variabel di PHP selalu diawali dengan symbol $. Variabel dapat terdiri dari string, number, atau array. Program4-1.php. <html> <body> <?php $txt="Hello World"; echo $txt; ?> </body> </html> Untuk menggabungkan dua atau lebih variabel, digunakan operator titik (.) Program4-2.php. <html> <body> <?php $txt1="Hello World"; $txt2="1234"; $Nilai1=1234; $Nilai2=4321; $Hasil=$Nilai1+Nilai2; echo $txt1 . " " . $txt2 ; echo $Hasil; ?> </body> </html> Konvensi penamaan variabel Variabel harus diawali oleh huruf atau garis bawah _. Variabel hanya dapat terdiri dari angka, huruf dan garis bawah (a-Z, 0-9, and _ ). Variabel tidak boleh menggandung spasi. Jika variabel akan ditulis sebagai dua kata, maka dapat menggunakan garis bawah untuk memisahkannya (contoh: $my_string), atau menggunakan huruf kapital (contoh: $myString).
Catatan. Perintah-perintah PHP dapat disisipkan dibagian manapun dalam dokumen html
++ --
Increment Decrement
Contoh x=2 x+2 x=2 5-x x=4 x*5 15/5 5/2 5%2 10%8 10%2 x=5 x++ x=5 x--
Operator Penugasan (Assignment Operators) Operator Contoh = x=y += x+=y -= x-=y *= x*=y /= x/=y %= x%=y Operator Perbandingan (Comparison Operators) Operator Keterangan == sama dengan != tidak sama dengan > lebih besar dari < kurang dari >= lebih besar atau sama dengan <= kurang dari atau sama dengan Operator Logika (Logical Operators) Operator Keterangan && and
Contoh 5==8 returns false 5!=8 returns true 5>8 returns false 5<8 returns true 5>=8 returns false 5<=8 returns true
||
or
not
x=6 y=3 (x==5 || y==5) returns false x=6 y=3 !(x==y) returns true
Program5-1.php. <html> <title>Operator Penjumlahan</title> <body> <?php $var1=10; $var2=20; print $var1 + $var2."<br>"; echo $var1 + $var2."<br>"; $Jum=$var1+$var2; echo $Jum; ?> </body> </html> Latihan Buat pogram dimana didalamnya perbandiungan dan logika terdapat operator aritmetika, penugasan,
Tugas-1 Perorangan Buat program berikut : 1. Rumus Luas Segitiga a.t 2. Rumus Pythagoras a2 + b2 = c2 3. Rumus Keliling Lingkaran
if...else statement digunakan jika kita akan mengeksekusi sebuah perintah jika kondisi bernilai true dan jika kondisi lainnya bernilai false. elseif statement digunakan bersama dengan if-else untuk mengeksekusi perintah jika salah satu dari berbagai kondisi bernilai true.
Statemen If...Else Sintak if (condition) code to be executed if condition is true; else code to be executed if condition is false; Program6-1.php <html> <body> <?php $d=date("D"); if ($d=="Fri") echo "Have a nice weekend!"; else echo "Have a nice day!"; ?> </body> </html> Program6-2.php <html> <body> <?php $d=date("A"); if ($d=="Fri") { echo "Hello!<br />"; echo "Have a nice weekend!"; echo "See you on Monday!"; } ?> </body> </html>
Statemen ElseIf Sintaks if (condition) code to be executed if condition is true; elseif (condition) code to be executed if condition is true; else code to be executed if condition is false; Program6-3.php <html> <title>Operator Aritmetika</title> <body> <?php $nilai = 95; $keterangan="Tidak Lulus"; if ($nilai>= 60) { $keterangan = "Lulus"; } printf("Nilai = %d<br>",$nilai); printf("keterangan= %s<br>",$keterangan); ?> </body> </html> Program6-4.php <html> <body> <?php $d=date("D"); if ($d=="Fri") echo "Have a nice weekend!"; elseif ($d=="Sun") echo "Have a nice Sunday!"; else echo "Have a nice day!"; ?> </body> </html> Latihan Tentukan GAPOK berdasarkan kriteria berikut : 1. Jika Lama_Kerja lebih dari 5 thn dan Gol A maka GAPOK Rp. 3 jt 2. Jika Lama_Kerja lebih dari 5 thn atau Gol A maka GAPOK Rp. 2,5 jt 3. Jika Lama_Kerja Kurang dari 5 thn dan Gol B maka GAPOK Rp. 2 jt 4. selain itu GAPOK 1,5 jt
Bab 7 Switch
Switch digunakan untuk melakukan suatu aksi dari beberapa aksi yang berbeda berdasarkan pada
satu atau lebih kondisi yang berbeda. Sintaks switch (expression) { case label1: code to be executed if expression = label1; break; case label2: code to be executed if expression = label2; break; default: code to be executed if expression is different from both label1 and label2; } Program7-1.php <html> <body> <?php switch ($x) { case 1: echo "Number 1"; break; case 2: echo "Number 2"; break; case 3: echo "Number 3"; break; default: echo "No number between 1 and 3";} ?> </body> </html> Latihan Buat Program berikut Bulan ke-1 Januari Bulan ke-2 Pebruari Bulan ke-3 Maret Bulan ke-4 April Bulan ke-5 Mei Bulan ke-5 Juni
Bulan ke-6 Juli Bulan ke-7 Agustus Bulan ke-8 September Bulan ke-9 Oktober Bulan ke-10 Nopember Bulen ke-12 Desember
Bab 9 Looping/Pengulangan
Statemen Looping statements digunakan untuk mengeksekusi blok program yang sama beberapa kali. Jenis-jenis Looping while do...while for foreach Statemen while while (condition) code to be executed; Program9-1.php <html> <body> <?php $i=1; while($i<=5) { echo "The number is " . $i . "<br />"; $i++; } ?> </body> </html> Statemen do...while do { code to be executed; } while (condition); Program9-2.php <html> <body> <?php $i=0; do { $i++; echo "The number is " . $i . "<br />"; }
10
Statemen for Statatemen for bekerja sebagai berikut : 1. Inisialisasi sebagai nilai awal 2. Kondisi diuji, jika bernilai true (benar),maka perulangan dilakukan dengan mengerjakan blok pernyataan jika bernilai false (salah) maka perulangan berhenti dan blok pernyataan dilompati 3. Jika blok pernyataan hanya terdiri satu baris maka tanda kurung kurawal dapat ditiadakan 4. Increment merupakan nilai penambahan atau pengurangan untuk mengulangi pengerjaan blok pernyataan jika kondisi masih terpenuhhi. For (initialization; condition; increment) { code to be executed; } Program9-3.php <html> <body> <?php for ($i=1; $i<=5; $i++) { echo "Hello World!<br />"; } ?> </body> </html>
Statemen foreach foreach (array as value) { code to be executed; } Program9-4.php <html> <body> <?php $arr=array("one", "two", "three"); foreach ($arr as $value) { echo "Value: " . $value . "<br />"; }
11
Latihan 1. Buat Program menggunakan statemen while dan statemen for dengan output sebagai berikut 1 3 5 7 9 11 13 15 17 2 4 8 16 32 64 Tugas-2 Perorangan 1. Buat program menggunakan statemen while dan statemen for dengan output sebagai berikut : a. -2 4 -8 16 -32 64 -128 b. 1 1 2 3 5 8 13 21 34 {bilangan fibonanci}
12
Bab 10 Fungsi/Function
Fungsi merupakan sebuah blok program yang dapat dieksekusi kapanpun kita memerlukannya. Program10-1.php <html> <body> <?php function writeMyName() { echo "Kai Jim Refsnes"; } writeMyName(); ?> </body> </html> Program10-2.php: <html> <body> <?php function writeMyName() { echo "Kai Jim Refsnes"; } echo "Hello world!<br />"; echo "My name is "; writeMyName(); echo ".<br />That's right, "; writeMyName(); echo " is my name."; ?> </body> </html> Ouput program: Hello world! My name is Kai Jim Refsnes. That's right, Kai Jim Refsnes is my name.
{ echo $fname . " Refsnes.<br />"; } echo "My name is "; writeMyName("Kai Jim"); echo "My name is "; writeMyName("Hege"); echo "My name is "; writeMyName("Stale"); ?> </body> </html> output program: My name is Kai Jim Refsnes. My name is Hege Refsnes. My name is Stale Refsnes. Program10-4.php <html> <body> <?php function writeMyName($fname,$punctuation) { echo $fname . " Refsnes" . $punctuation . "<br />"; } echo "My name is "; writeMyName("Kai Jim","."); echo "My name is "; writeMyName("Hege","!"); echo "My name is "; writeMyName("Stle","..."); ?> </body> </html> output: My name is Kai Jim Refsnes. My name is Hege Refsnes! My name is Stle Refsnes...
Fungsi yang mengembalikan sebuah nilai Program10-5.php <html> <body> <?php function add($x,$y) {
14
$total = $x + $y; return $total; } echo "1 + 16 = " . add(1,16) ?> </body> </html> output : 1 + 16 = 17
15
16
Mengapa menggunakan $_GET? Note: Dengan menggunakan $_GET, nama variabel dan nilainya akan ditampilkan di address bar. Note: $_GET tidak dapat digunakan untuk mengirim variabel yang besar, nilai yang dapat dikirim tidak dapat melebihi 100 karakter. Variabel $_REQUEST Variabel $_REQUEST terdiri baik $_GET, $_POST, dan $_COOKIE. Variabel $_REQUEST dapat digunakan untuk mengambil data dari form yang dikirim mengunakan variabel $_GET maupun $_POST. Program12-3.php Welcome <?php echo $_REQUEST["name"]; ?>.<br /> You are <?php echo $_REQUEST["age"]; ?> years old!
17
Mengapa menggunakan $_POST? Nama dan nilai variabel yang dikirim tidak diperlihatkan pada URL. Jumlah variabel yang dikirim tidak terbatas. Variabel $_REQUEST Program13-3.php Welcome <?php echo $_REQUEST["name"]; ?>.<br /> You are <?php echo $_REQUEST["age"]; ?> years old!
18
Timestamp Timestamp adalah jumlah detik sejak January 1, 1970 00:00:00 GMT. Juga dikenal sebagai Unix Timestamp. Format Tanggal
Program14-1.php <?php echo date("Y/m/d"); echo "<br />"; echo date("Y.m.d"); echo "<br />"; echo date("Y-m-d"); ?> output: 2006/07/11 2006.07.11 2006-07-11 Fungsi mktime() akan memberikan nilai Unix timestamp untuk tanggal tertentu. Sintaks mktime(hour,minute,second,month,day,year,is_dst) Program14-2.php <?php $tomorrow = mktime(0,0,0,date("m"),date("d")+1,date("Y")); echo "Tomorrow is ".date("Y/m/d/", $tomorrow); ?> output:
PHP & MySql 19
Tomorrow is 2006/07/12
<h1>Welcome to my home page</h1> <p>Some text</p> </body> </html> Fungsi require() Fungsi require() sama dengan include(), tetapi berbeda dalam cara penanganan kesalahan. Fungsi include() akan menghasilkan peringatan (dan program akan melanjutkan ekseskusinya) sedangkan fungsi require() akan menghasilkan fatal error dan menghentikan program. Program15-3.php (program contoh error pada penggunaan fungsi include()). <html> <body> <?php include("wrongFile.php"); echo "Hello World!"; ?> </body> </html> Error message: Warning: include(wrongFile.php) [function.include]: failed to open stream: No such file or directory in C:\home\website\test.php on line 5 Warning: include() [function.include]: Failed opening 'wrongFile.php' for inclusion (include_path='.;C:\php5\pear') in C:\home\website\test.php on line 5 Hello World! Program15-4.php (program contoh error pada penggunaan fungsi require()) <html> <body> <?php require("wrongFile.php"); echo "Hello World!"; ?> </body> </html> Error message: Warning: require(wrongFile.php) [function.require]: failed to open stream: No such file or directory in C:\home\website\test.php on line 5 Fatal error: require() [function.require]:
21
or
exit("Unable
to
open
file!");
22
Menutup File Program16-3.php <?php $file = fopen("test.txt","r"); //some code to be executed fclose($file); ?>
Memeriksa EOF (End Of File) Catatan: Kita tidak dapat membaca file yang terbuka dalam mode w, a, dan x! if (feof($file)) echo "End of file"; Membaca file baris per baris (fgets()) Program16-4.php <?php $file = fopen("welcome.txt", "r") or exit("Unable to open file!"); //Output a line of the file until the end is reached while(!feof($file)) { echo fgets($file). "<br />"; } fclose($file); ?>
Membaca file karakter per karakter (fgetc()) Program16-5.php <?php $file=fopen("welcome.txt","r") or exit("Unable to open file!"); while (!feof($file)) { echo fgetc($file); } fclose($file); ?>
23
24
Pembatasan Upload File Program17-2.php <?php if (($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") && ($_FILES["file"]["size"] < 20000)) { if ($_FILES["file"]["error"] > 0) { echo "Error: " . $_FILES["file"]["error"] . "<br />"; } else { echo "Upload: " . $_FILES["file"]["name"] . "<br />"; echo "Type: " . $_FILES["file"]["type"] . "<br />"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; echo "Stored in: " . $_FILES["file"]["tmp_name"]; } } else { echo "Invalid file"; } ?>
Menyimpan File yang telah di-Upload Program17-3.php <?php if (($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") && ($_FILES["file"]["size"] < 20000)) { if ($_FILES["file"]["error"] > 0) { echo "Return Code: " . $_FILES["file"]["error"] . "<br />"; } else { echo "Upload: " . $_FILES["file"]["name"] . "<br />"; echo "Type: " . $_FILES["file"]["type"] . "<br />"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />"; if (file_exists("upload/" . $_FILES["file"]["name"])) { echo $_FILES["file"]["name"] . " already exists. "; } else { move_uploaded_file($_FILES["file"]["tmp_name"],
PHP & MySql 25
"upload/" . $_FILES["file"]["name"]); echo "Stored in: " . "upload/" . $_FILES["file"]["name"]; } } } else { echo "Invalid file"; } ?>
26
Menghapus Cookie Program18-4.php <?php // set the expiration date to one hour ago setcookie("user", "", time()-3600); ?>
PHP & MySql 27
Bagaimana jika browser yang kita gunakan tidak mendukung Cookie Gunakan pasangan form input untuk mengirim data dan form retrieve untuk mengambil data seperti contoh di bawah ini. Program18-5.php <html> <body> <form action="welcome.php" method="post"> Name: <input type="text" name="name" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> </body> </html> welcome.php. <html> <body> Welcome <?php echo $_POST["name"]; ?>.<br /> You are <?php echo $_POST["age"]; ?> years old. </body> </html>
28
<body> <?php //retrieve session data echo "Pageviews=". $_SESSION['views']; ?> </body> </html> Output: Pageviews=1 Pada contoh di bawah ini, kita akan membuat counter page-views sederhana. Fungsi isset() akan melakukan pengecekan terhadap variabel views apakah telah dibuat. Jika views telah tersedia, maka kita dapat melakukan proses penambahan pada counter. Jika views tidak ada, maka kita akan membuat variabel views dan mensetnya dengan 1. Program19-3.php <?php session_start(); if(isset($_SESSION['views'])) $_SESSION['views']=$_SESSION['views']+1; else $_SESSION['views']=1; echo "Views=". $_SESSION['views']; ?> Menghapus Session Jika kita ingin menghapus beberapa data session, kita dapat menggunakan fungsi unset() atau fungsi session_destroy(). Fungsi unset() digunakan untuk membebaskan variabel session tertentu. Program19-4.php <?php unset($_SESSION['views']); ?> Kita juga dapat menghapus keseluruhan session dengan menggunakan fungsi session_destroy(). Program19-5.php <?php session_destroy(); ?> Catatan: session_destroy() akan me-reset session kita dan kita akan kehilangan seluruh data session yang telah tersimpan.
30
Query Dengan MySQL, kita dapat melakukan query untuk mendapatkan informasi tertentu dari database. Contoh query SELECT LastName FROM Persons Query di atas akan menampilkan semua data pada field LastName dari tabel Persons. LastName Hansen Svendson Pettersen
31
Program23-1.php <?php $con = mysql_connect("localhost","root",""); if (!$con) { die('Could not connect: ' . mysql_error()); } // some code ?>
Menutup Koneksi Program23-2.php <?php $con = mysql_connect("localhost","root",""); if (!$con) { die('Could not connect: ' . mysql_error()); } // some code mysql_close($con); ?>
32
Membuat Tabel CREATE TABLE table_name ( column_name1 data_type, column_name2 data_type, column_name3 data_type, ....... ) Program24-2.php <?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } // Create database if (mysql_query("CREATE DATABASE my_db",$con)) { echo "Database created"; } else { echo "Error creating database: " . mysql_error();
33
} // Create table in my_db database mysql_select_db("my_db", $con); $sql = "CREATE TABLE Person ( FirstName varchar(15), LastName varchar(15), Age int )"; mysql_query($sql,$con); mysql_close($con); ?> Tipe Data di MySQL Numeric Data Types int(size) smallint(size) tinyint(size) mediumint(size) bigint(size) decimal(size,d) double(size,d) float(size,d) Description Integers terus saja. Maksimum jumlah digit dapat ditentukan dalam parameter ukuran
Hold numbers with fractions. The maximum number of digits can be specified in the size parameter. The maximum number of digits to the right of the decimal is specified in the d parameter Description Holds a fixed length string (can contain letters, numbers, and special characters). The fixed size is specified in parenthesis Holds a variable length string (can contain letters, numbers, and special characters). The maximum size is specified in parenthesis Holds a variable string with a maximum length of 255 characters Holds a variable string with a maximum length of 65535 characters Holds a variable string with a maximum length of 16777215 characters Holds a variable string with a maximum length of 4294967295 characters
varchar(size)
Date Data Types Description date(yyyy-mm-dd) Holds date and/or time datetime(yyyy-mm-dd hh:mm:ss) timestamp(yyyymmddhhmmss) time(hh:mm:ss) Misc. Data Types
PHP & MySql
Description
34
enum(value1,value2,ect)
set
ENUM is short for ENUMERATED list. Can store one of up to 65535 values listed within the ( ) brackets. If a value is inserted that is not in the list, a blank value will be inserted SET is similar to ENUM. However, SET can have up to 64 list items and can store more than one choice
Primary Keys dan Auto Increment Fields $sql = "CREATE TABLE Person ( personID int NOT NULL AUTO_INCREMENT, PRIMARY KEY(personID), FirstName varchar(15), LastName varchar(15), Age int )"; mysql_query($sql,$con);
35
Insert Data From a Form Into a Database Program25-2.php <html> <body> <form action="insert.php" method="post"> Firstname: <input type="text" name="firstname" /> Lastname: <input type="text" name="lastname" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> </body> </html> insert.php <?php $con = mysql_connect("localhost","root",""); if (!$con)
36
{ die('Could not connect: ' . mysql_error()); } mysql_select_db("my_db", $con); $sql="INSERT INTO person (FirstName, LastName, Age) VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[age]')"; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } echo "1 record added"; mysql_close($con) ?>
37
mysql_select_db("my_db", $con); $result = mysql_query("SELECT * FROM person"); echo "<table border='1'> <tr> <th>Firstname</th> <th>Lastname</th> </tr>"; while($row = mysql_fetch_array($result)) { echo "<tr>"; echo "<td>" . echo $row['FirstName'] . "</td>"; echo "<td>" . echo $row['LastName'] . "</td>"; echo "</tr>"; } echo "</table>"; mysql_close($con); ?> The output of the code above will be: Firstname Lastname Glenn Quagmire Peter Griffin
39
Note: SQL statements are not case sensitive. WHERE is the same as where. To get PHP to execute the statement above we must use the mysql_query() function. This function is used to send a query or command to a MySQL connection.
Example
The following example will select all rows from the "Person" table, where FirstName='Peter':
<?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("my_db", $con); $result = mysql_query("SELECT * FROM person WHERE FirstName='Peter'"); while($row = mysql_fetch_array($result)) { echo $row['FirstName'] . " " . $row['LastName']; echo "<br />"; } ?>
The output of the code above will be:
Peter Griffin
40
BAB 26
Example
The following example selects all the data stored in the "Person" table, and sorts the result by the "Age" column:
<?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("my_db", $con); $result = mysql_query("SELECT * FROM person ORDER BY age"); while($row = mysql_fetch_array($result)) { echo $row['FirstName'] echo " " . $row['LastName']; echo " " . $row['Age']; echo "<br />"; } mysql_close($con); ?>
The output of the code above will be:
41
BAB 27
Example
Earlier in the tutorial we created a table named "Person". Here is how it looks: FirstName Peter Glenn LastName Griffin Quagmire Age 35 33
<?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("my_db", $con); mysql_query("UPDATE Person SET Age = '36' WHERE FirstName = 'Peter' AND LastName = 'Griffin'"); mysql_close($con); ?>
After the update, the "Person" table will look like this: FirstName Peter Glenn LastName Griffin Quagmire Age 36 33
42
BAB 28
Example
Earlier in the tutorial we created a table named "Person". Here is how it looks: FirstName Peter Glenn LastName Griffin Quagmire Age 35 33
The following example deletes all the records in the "Person" table where LastName='Griffin':
<?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("my_db", $con); mysql_query("DELETE FROM Person WHERE LastName='Griffin'"); mysql_close($con); ?>
After the deletion, the table will look like this: FirstName Glenn LastName Quagmire Age 33
43