0% menganggap dokumen ini bermanfaat (0 suara)
9 tayangan15 halaman

Pemrograman Web Dinamis

PEMROGRAMAN WEB DINAMIS

Diunggah oleh

heniandriyani13
Hak Cipta
© © All Rights Reserved
Kami menangani hak cipta konten dengan serius. Jika Anda merasa konten ini milik Anda, ajukan klaim di sini.
Format Tersedia
Unduh sebagai DOCX, PDF, TXT atau baca online di Scribd
0% menganggap dokumen ini bermanfaat (0 suara)
9 tayangan15 halaman

Pemrograman Web Dinamis

PEMROGRAMAN WEB DINAMIS

Diunggah oleh

heniandriyani13
Hak Cipta
© © All Rights Reserved
Kami menangani hak cipta konten dengan serius. Jika Anda merasa konten ini milik Anda, ajukan klaim di sini.
Format Tersedia
Unduh sebagai DOCX, PDF, TXT atau baca online di Scribd
Anda di halaman 1/ 15

PEMROGRAMAN WEB DINAMIS

PHP Arrays

Array digunakan untuk menyimpan satu atau lebih nilai pada sebuah nama variabel.

Jenis-jenis Array

 Numeric array – Array dengan sebuah numeric ID key.


 Associative array - Array dimana setiap ID-nya berasosiasi dengan suatu nilai.
 Multidimensional array - Array yang terdiri dari satu atau lebih array.
Numeric Array

Contoh 1

Pada contoh ini kunci ID secara otomatis di beri suatu nilai.

$names = array("Peter","Quagmire","Joe");

Example 2

Pada contoh ini kita memberikan nilai pada kunci ID secara manual.

$names[0] = "Peter";

$names[1] = "Quagmire";

$names[2] = "Joe";

Program8-1.php

<?php

$names[0] = "Peter";

$names[1] = "Quagmire";

$names[2] = "Joe";

echo $names[1] . " and " . $names[2] .

" are ". $names[0] . "'s neighbors";

?>
PEMROGRAMAN WEB DINAMIS

Output program:

Quagmire and Joe are Peter's neighbors

Associative Arrays

Contoh 1

Pada contoh ini kita menggunakan sebuah array untuk memberikan nilai umur pada beberapa
orang yang berbeda.

$ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);

Output program:

Peter is 32 years old.

Multidimensional Arrays

Contoh 1 cara inisialisasi multidimensional array

$families = array

"Griffin"=>array

"Peter",

"Lois",

"Megan",

),

"Quagmire"=>array

"Glenn"

),

"Brown"=>array
PEMROGRAMAN WEB DINAMIS

"Cleveland",

"Loretta",

"Junior"

);

Array di atas akan terlihat seperti di bawah ini jika dituliskan ke output.

Array

[Griffin] => Array

[0] => Peter

[1] => Lois

[2] => Megan

[Quagmire] => Array

[0] => Glenn

[Brown] => Array

[0] =>Cleveland

[1] => Loretta

[2] => Junior

)
PEMROGRAMAN WEB DINAMIS

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;
PEMROGRAMAN WEB DINAMIS

while (condition);

Statemen for

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>

PHP $_GET

variabel $_GET digunakan untuk mengambil nilai dari form menggunakan metode
“get”.

Variabel $_GET

Program12-1.php

<form action="Program12-2.php" method="get">

Name: <input type="text" name="name" />


PEMROGRAMAN WEB DINAMIS

Age: <input type="text" name="age" />

<input type="submit" />

</form>

Ketika user mengklik tombol “submit”, URL yang dikirm akan berbentuk seperti di bawah
ini.

http://www.w3schools.com/welcome.php?name=Peter&age=37

Program12-2.php

Welcome <?php echo $_GET["name"]; ?>.<br />

You are <?php echo $_GET["age"]; ?> years old!

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!

PHP Include File


Server Side Includes (SSI) digunakan untuk menyimpan fungsi, header, footer, atau
elemen-elemen yang dapat digunakan pada halaman yang berlainan.
Server Side Includes
Fungsi include()
Fungsi include() akan mengambil semua teks pada file include dan mengkopinya ke file
tujuan.

Program15-1.php
Diasumsikan bahwa kita mempunyai file header dengan nama “header.php”. Untuk memakai
file ini pada halaman web kita seperti di bawah ini.
<html>
PEMROGRAMAN WEB DINAMIS

<body>
<?php include("header.php"); ?>
<h1>Welcome to my home page</h1>
<p>Some text</p>
</body>
</html>
Program15-2.php
Sekarang, kita asumsikan bahwa kita mempunyai file standar menu yang akan digunakan
pada seluruh halaman (file include biasanya berektensi *.php). Penggunaannya seperti di
bawah ini.
<html>
<body>
<a href=" default.php">Home</a> |
<a href=" about.php">About Us</a> |
<a href=" contact.php">Contact Us</a>

Ketiga file, "default.php", "about.php", dan "contact.php" semuanya akan di-include-kan


pada file "menu.php". Berikut ini program "default.php":
<?php include("menu.php"); ?>
<h1>Welcome to my home page</h1>
<p>Some text</p>
</body>
</html>

Dan hasilnya pada browser adalah sebagai berikut.


<html>
<body>
<a href="default.php">Home</a> |
<a href="about.php">About Us</a> |
<a href="contact.php">Contact Us</a>
<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>
PEMROGRAMAN WEB DINAMIS

</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]:
Failed opening required 'wrongFile.php'
(include_path='.;C:\php5\pear')
in C:\home\website\test.php on line 5
PHP File Handling
Dalam PHP, fungsi fopen() digunakan untuk membuka file.
Membuka File

Program16-1.php
<html>
<body>
<?php
$file=fopen("welcome.txt","r");
?>
</body>
</html>

Mode pembukaan file


Mode Keterangan
PEMROGRAMAN WEB DINAMIS

r Read only. Starts at the beginning of the file

r+ Read/Write. Starts at the beginning of the file

w Write only. Opens and clears the contents of file; or creates a new file if it
doesn't exist

w+ Read/Write. Opens and clears the contents of file; or creates a new file if it
doesn't exist

a Append. Opens and writes to the end of the file or creates a new file if it
doesn't exist

a+ Read/Append. Preserves file content by writing to the end of the file

x Write only. Creates a new file. Returns FALSE and an error if file already
exists

x+ Read/Write. Creates a new file. Returns FALSE and an error if file


already exists

Catatan: Jika fopen() tidak dapat membuka file, maka akan mengembalikan nilai 0 (false).

Program16-2.php
<html>
<body>
<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
?>
</body>
</html>

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
PEMROGRAMAN WEB DINAMIS

$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);
?>

PHP File Upload

Dengan PHP, kita dapat meng-upload file ke server.


Membuat Form Upload-File

Program17-1.php
<html>
<body>
<form action="upload_file.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>

Membuat Skrip Upload

upload_file.php
<?php
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"];
PEMROGRAMAN WEB DINAMIS

}
?>

Dengan menggunakan array global PHP $_FILES kita dapat meng-upload file dari client ke server.
Parameter pertama adalah nama input dan yang kedua adalah dapat berupa "name", "type", "size", "tmp_name"
atau "error". Seperti berikut ini:
 $_FILES["file"]["name"] – Nama file yang akan di-upload.
 $_FILES["file"]["type"] – Type dari file yang akan di-upload.
 $_FILES["file"]["size"] – Ukuran dalam byte dari file yang akan di-upload.
 $_FILES["file"]["tmp_name"] – Nama kopian sementara dari file yang disimpan di server.
 $_FILES["file"]["error"] – Kode error dari file yang di-upload.
Hal ini sangat mudah untuk dilakukan. Untuk alas an keamanan, kita seharusnya menerapkan kebijakan siapa
saja user yang dapat meng-upload file ke server.

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"],
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
}
}
else
{
echo "Invalid file";
}
?>

Membuat Database dan Tabel

Membuat Database

CREATE DATABASE database_name


PEMROGRAMAN WEB DINAMIS

Program24-1.php
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
if (mysql_query("CREATE DATABASE my_db",$con))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
mysql_close($con);
?>

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();
}
// 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


PEMROGRAMAN WEB DINAMIS

Numeric Data Types Description

int(size) Hold integers only. The maximum number of digits can be


smallint(size) specified in the size parameter
tinyint(size)
mediumint(size)
bigint(size)

decimal(size,d) Hold numbers with fractions. The maximum number of digits can
double(size,d) be specified in the size parameter. The maximum number of
float(size,d) digits to the right of the decimal is specified in the d parameter

Textual Data Types Description

char(size) Holds a fixed length string (can contain letters, numbers, and
special characters). The fixed size is specified in parenthesis

varchar(size) Holds a variable length string (can contain letters, numbers, and
special characters). The maximum size is specified in parenthesis

tinytext Holds a variable string with a maximum length of 255 characters

text Holds a variable string with a maximum length of 65535


blob characters

mediumtext Holds a variable string with a maximum length of 16777215


mediumblob characters

longtext Holds a variable string with a maximum length of 4294967295


longblob characters

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)

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),
PEMROGRAMAN WEB DINAMIS

Age int
)";
mysql_query($sql,$con);

Kode Simpan pada PHP :

INSERT INTO table_name

VALUES (value1, value2,....)

Kode Update pada PHP :

UPDATE table_name

SET column_name = new_value

WHERE column_name = some_value

Kode Delete Pada PHP :

DELETE FROM table_name

WHERE column_name = some_value

Cara Expor file di Phpmyadmin :

Pilih database yang akan di expor, kemudian klik expor, dan klik buton kirim, kemudian hasil
yang telah di expor akan muncul di file download komputer anda.

Cara Impor file di Phpmyadmin :

Masuk ke database kalian yang ada di phpmyadmin, kemudian klik impor, setelah itu pilih
file yang akan di upload (file tersebut berbentuk .sql), kemudain setelah selesai klik kirim.

Tugas :

Buat Aplikasi sesuai kelompok masing-masing !

UTS praktek: Kumpulkan sebagian aplikasi yang telah dibuat

UAS praktek: Kumpulkan keseluruhan Aplikasi


PEMROGRAMAN WEB DINAMIS

Anda mungkin juga menyukai