Membuat form
untuk pencarian internal website menggunakan Dreamweaver? Mungkin ga ya?
Jelas sangat
mungkin. Pada tutorial ini, Anda akan belajar membuat search engine untuk
internal website Anda. Ada dua file satu tabel data yang akan kita gunakan
untuk menampilkan form pencarian dan hasil pencarian, file dan database
tersebut adalah:
- form.php (adalah form untuk mengetikkan pencarian kata
kunci)
- cari.php (adalah halaman yang digunakan untuk menampilkan
hasil pencarian)
- products.sql (tabel data MySQL berisi data tentang produk.
Anda dapat menggunakan database lainnya jika Anda mau)
NOTE: LIHAT BAGIAN BAWAH DARI TUTORIAL INI, DI SANA TERDAPAT BASIC SCRIPT
PHP DAN MYSQL UNTUK KETIGA FILE DI ATAS
Untuk
memulai tutorial ini, pastikan Anda telah:
- Membuat
Site Definition terlebih dahulu (jika Anda menggunakan Dreamweaver CS4 ke
bawah) atau Site Setup (jika Anda menggunakan Dreamweaver CS5). Dalam
tutorial ini Site Definition disimpan dalam folder search_engine.
- Membuat
database products dan mengimport tabel data products melalui phpMyAdmin
- Telah
membuat koneksi database PHP MySQL
Langkah selanjutnya, (File form.php):
Lihat script
aslinya di bagian bawah tutorial ini.
Java Web
Media
- Lihat
pada file form.php di bawah ini, maka Anda akan melihat form
action-nya file cari.php. <form id=”form1″
name=”form1″ method=”post” action=”cari.php“>.
- Lalu
pada label input, maka Anda akan menemukan id=”cari” (lihat
kode ini <input type=”text” name=”cari”
id=”cari” />). ID=”cari” inilah yang nantinya akan kita
jadikan sebagai variabel form untuk pencarian.
- Anda
tidak perlua melakukan penambahan apa-apa pada file ini.
Langkah selanjutnya, (File cari.php):
Java Web
Media
Pada file
ini, kita akan menampilkan hasil pencarian. Berikut langkah-langkahnya:
- Pastikan
Anda telah membuat Site Definiton dan database connection (lihat search_engine.php)
- Buka
file cari.php
- Klik Insert
> Data Objects > Recordset. Di sini Anda akan membuat Recordset
dengan filter form variabel dengan id=”cari”. Jendela Recordset akan
segera keluar.
- Name:
Recordset1 (Anda dapat mengubah dengan nama lain)
- Connection:
search_engine
- Table:
products
- Columns:
All
- Filter:
product Name (Pilihlah dengan mengklik pop-up menu, secara
otomatis Dreamweaver akan menempatkan URL Parameter sebagai pilihan
Default, lalu (=) dan productName).
- Pada URL
Parameter, gantilah menjadi Form Variable dengan
mengklik pop-up menu. Lalu pada simbol sama dengan (=) ubahlah
menjadi contains. Lalu pada productName, hapus
tulisan tersebut lalu ketik cari (ingat, Anda telah
mendefinisikan id=”cari” pada halaman form.php sebelumnya).
- Sort:
productName dan Ascending
(ini artinya nama produk akan ditampilkan sesuai urutan abjad).
- Klik OK
Java Web
Media
Langkah selanjutnya, (File cari.php):
Anda telah
berhasil membuat Recordset1. Langkah selanjutnya adalah melakukan
Bindings data. Berikut langkah-langkahnya:
- Pastikan
Anda masih membuka file cari.php
- Klik Windows
> Bindings. Di bagian kanan dari layar Anda akan muncul tabel data
yang tadi telah kita buat Recordset-nya. Klik tanda plus (+) pada tulisan “Recordset
(Recordset1)”. Ini artinya Anda melakukan expand terhadap semua
fields/kolom dari tabel database.
- Melalui
Design View, seleksi tulisan “Nama Products“, lalu
hapuslah teks tersebut.
- Melalui
kolom Bindings, klik dan tahan productName yang bertanda
petir, lalu drag menuju area teks “Nama Products” yang
tadi telah Anda hapus.
- Hapus
teks “Deskripsi produts” lalu dari Bindings, klik dan
tahan Description yang bertanda petir , lalu
drag menuju area teks yang baru saja Anda hapus.
- Melalui
Code View, seleksi kode berikut ini: <hr/>
<h3><?php echo $row_Recordset1['productName']; ?></h3>
<p><?php echo $row_Recordset1['description']; ?></p>
<hr/>
- Klik Insert > Data Objects > Repeat Region. Window Repeat
Region Akan keluar.
- Pada menu Recordset: Recordset1 (klik pop-up menu untuk
memilih)
- Lalu pada Show: 5 Records at a time (secara default Dreamweaver
akan menulis angka 10 untuk repeat region, ubahlah angka 10 tersebut
menjadi 5. Ini artinya Anda akan menampilkan 5 baris tabel data untuk
setiap pencarian). Klik OK jika sudah selesai.
- Melalui Code View, letakkan kursor Anda setelah kode
ini: <?php
} while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?>. Pastikan
kursor Anda berada sebelum atau di dalam tag </body>. Lalu
tekan Enter.
- Klik Insert
> Data Objects > Recordset Paging > Recordset Navigation Bar.
Maka jendela Recordset Paging akan keluar.
- Pada
menu Recordser: Recordset1, lalu Display Using: Text. Klik OK
untuk menyelesaikan proses ini.
- Simpan
file cari.php
- Halaman
hasil pencarian cari.php telah berhasil Anda selesaikan.
- Lakukan
pengujian dengan membuka halaman form.php melalui browser atau http://localhost/search_engine/form.php.
Lalu cobalah mengetikkan beberapa kata kunci, maka Anda akan diarahkan ke
halaman cari.php
NOTE:
Tutorial ini masih menggunakan Simple Recordset dan tidak ada penambahan
dynamic link untuk menampilkan detail dari setiap produk.
Berikut
adalah file-file PHP yang kita butuhkan
FORM.PHP
<!DOCTYPE
html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
<title>Form Pencarian</title>
</head>
<body>
<h1>Form Search Engine
</h1>
<form id=”form1″ name=”form1″ method=”post” action=”cari.php”>
<label><strong>Cari di Website ini:</strong>
<input type=”text” name=”cari” id=”cari” />
</label>
<input type=”submit” name=”submit” id=”submit” value=”Cari” />
</form>
<p> </p>
</body>
</html>
CARI.PHP
<!DOCTYPE
html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
<title>Hasil Pencarian</title>
</head>
<body>
<h1>Hasil Pencarian….
</h1><hr/>
<h3><a href=”#”>Nama Products</a></h3>
<p>Deskripsi Produts</p>
<hr/>
</body>
</html>
PRODUCTS.SQL
– phpMyAdmin
SQL Dump
– version 3.2.4
– http://www.phpmyadmin.net
–
– Host: localhost
– Generation Time: Mar 29, 2011 at 12:34 p.m.
– Server version: 5.1.41
– PHP Version: 5.3.1
SET
SQL_MODE=”NO_AUTO_VALUE_ON_ZERO”;
/*!40101 SET
@OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
–
– Database: `cosmofarmer`
–
–
——————————————————–
–
– Table structure for table `products`
–
CREATE TABLE
IF NOT EXISTS `products` (
`productID` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
`productName` varchar(64) CHARACTER SET utf8 NOT NULL,
`price` double(10,2) NOT NULL,
`description` text CHARACTER SET utf8 NOT NULL,
`inventory` varchar(12) CHARACTER SET utf8 NOT NULL,
`vendorID` mediumint(9) NOT NULL,
`categoryID` mediumint(9) NOT NULL,
`image` varchar(255) CHARACTER SET utf8 NOT NULL,
`onSale` tinyint(4) NOT NULL,
PRIMARY KEY (`productID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=29 ;
–
– Dumping data for table `products`
–
INSERT INTO
`products` (`productID`, `productName`, `price`, `description`, `inventory`,
`vendorID`, `categoryID`, `image`, `onSale`) VALUES
(1, ‘Bathtub Hydroponic Tomato Starts’, 45.95, ‘Raising hydroponic tomatos from
seed is a difficult and time consuming process. Get a head start with these
ready to use tomato starts. Just fill up the bathtub, turn on the gro-light and
plop it in.’, ‘in stock’, 5, 1, ‘tomato_starts.jpg’, 1),
(2, ‘Gotcha Cucaracha’, 2.95, ‘Let this urban pest become your friend. The
cockroach makes a great natural pesticide protecting your indoor agriculture
with its fierce territorial instincts’, ‘out of stock’, 2, 4, ‘cockroach.jpg’,
0),
(3, ‘Genetically Modified Ladybugs’, 145.95, ‘Ladybugs have always been a
friend to gardeners who wish to keep their gardens pest free. These genetically
modified warriors aren”t your mom”s ladybugs. Equipped with street saavy, a
five year life span, and mandibles made of titanium alloy, these bugs WILL
spell the end of your pest troubles. Not recommended for pet owners.’, ‘in
stock’, 2, 4, ‘ladybugs.jpg’, 0),
(4, ‘Porsche Ball Widger’, 89.55, ‘German engineered of space-age aluminum this
cross between a trowel and a dibber is the perfect tool for levering plants
from their pots. It”s sophisticated design just shouts “Urban Ag-Chic.”‘, ‘in
stock’, 13, 3, ‘widger.jpg’, 1),
(5, ‘Kudzu Saplings’, 1.29, ‘Looking for that instant “been growing for years”
look? Fast growing Kudzu will turn your apartment into a tropical wilderness in
a matter of weeks. Highly recommended for homesick southerners.’, ‘in stock’,
7, 1, ‘kudzu.jpg’, 1),
(6, ‘CosmoFarmer 2.0 Tee’, 25.95, ‘Celebrate the urban-ag revolution with this
100% organic, T-shirt. This fashionable Tee designed by a famous NY designer
shouts urban hipness. It”s also completely edible with a protein content of
20g.’, ‘in stock’, 7, 5, ‘cosmo_tee1.jpg’, 0),
(7, ‘John Dear T-Shirt’, 19.95, ‘Show your love of heavy machinery. ‘, ‘in
stock’, 11, 5, ‘deer_t.jpg’, 0),
(8, ‘SOHO Bathtub Hydroponic Starter Kit’, 249.95, ‘The original…and still the
best. Urban Farming Collective”s SOHO Bathtub Hydroponic Starter Kit is the
most effective and stylish hydroponic system ever devised. Aparment Compost
magazine raves: “It looks like an iPod for the bathtub!”‘, ‘out of stock’, 1,
3, ‘soho_kit.jpg’, 1),
(9, ‘Distressed Denim Rose Bush’, 39.95, ‘Finally, a rose to match your urban
lifestyle. This unique hybrid has the texture and appearance of denim. Process
especially for Gap Plants, the distressed look, which includes dirt marks and
small tears, makes this rose look like you”ve had it around for years. Even though
it”s brand new!’, ‘in stock’, 9, 1, ‘none.gif’, 0),
(10, ‘Carpetorium Pratensis Seeds’, 4.95, ‘The must luxurious of indoor lawns
are now available as seeds. There”s nothing as satisfying as growing an indoor
lawn from scratch. We recommend the Carpetorium Pratensis carpet patch kit to
fill in areas of no-growth or heavy wear.’, ‘in stock’, 3, 2, ‘seeds.jpg’, 0),
(11, ‘Carpetorium Pratensis carpet patch kit’, 29.95, ‘Nothing”s worse than a
spotty indoor lawn. Whether it”s from heavy wear, low sunlight or incomplete
watering, holes in your Carpetorium Pratensis are simply unattractive. Patch
those holes quickly and easily with the Carpetorium Pratensis carpet patch
kit.’, ‘in stock’, 3, 1, ‘pratensis.jpg’, 1),
(12, ‘CAT Indoor Lawn Tractor’, 598.95, ‘The ultimate in convenient lawn
maintenance. This lawn tractor has a zero turning radius that makes it easy to
navigate around sofas, coffee tables, and small pets. The dual hydrostatic
transmissions frees you from any gear changes, and the redesigned emission
system is much safer than previous models.’, ‘out of stock’, 12, 3, ‘none.gif’,
0),
(13, ‘John Dear Deluxe Apartment Mower’, 154.88, ‘An all around excellent
indoor mower at an affordable price. The fine blades turn even large weeds into
tiny cuttings, perfect for composting or salad garnish’, ‘in stock’, 11, 3,
‘dear_mower.jpg’, 1),
(14, ‘Periwinkle Daisy Seeds’, 4.95, ‘Periwinkle. It”s the new black…not that
black flowers were ever in. But Periwinkle ones will be.’, ‘in stock’, 3, 2,
‘seeds.jpg’, 0),
(15, ‘Chardonnay Yellow Daisy Seeds’, 4.95, ‘Chardonnay. It”s the new
periwinkle.’, ‘in stock’, 3, 2, ‘seeds.jpg’, 0),
(16, ‘Cabarnet Begonia Seeds’, 4.95, ‘Cabarnet. It”s new the Chardonnay!’, ‘in
stock’, 3, 2, ‘seeds.jpg’, 0),
(20, ‘Titanium Dhalia Seeds’, 29.95, ‘Perfect companion to a Capresso Espresso
machine, Bosch dishwasher, or any other stainless steel appliance.’, ‘in
stock’, 7, 2, ‘seeds,jpg’, 0),
(18, ‘No Sunlight Super Carrot seeds’, 4.95, ‘For dark industrial basement
apartments, these special hybrids require nearly no light, but, amazingly, give
you the power to see in the dark. ‘, ‘in stock’, 5, 2, ‘seeds.jpg’, 0),
(19, ‘Broccolini’, 12.95, ‘Plant these exquisite starts in a porcelain planter
on your favorite coffee table. It”s like edible bonsai!’, ‘in stock’, 9, 1,
‘broccoli.jpg’, 1),
(21, ‘Tuscan Sun Rose Seeds’, 29.95, ‘Bongiorno! Wake up to the beauty of this
mediterranean love.’, ‘in stock’, 10, 2, ‘seeds.jpg’, 1),
(22, ‘CAT Mini-Combine 5000′, 999.99, ‘We know you”re a busy professional. Time
is precious and you just don”t have the time to labor over your apartment grain
crops using traditional methods. The CAT Mini-Combine 5000, simplifies the
tasks of harvesting, threshing and cleaning grain. This precision machine,
co-designed with Porsche AG, is fast, lean and beautiful. Runs on normal 120
volt current. (European adapter included.)’, ‘in stock’, 12, 3, ‘combine.jpg’,
1),
(23, ‘Diamond Handled Trowel’, 999.99, ‘Even though you like to get your hands
dirty, there”s no reason to skimp on the tools of your beloved hobby. The
diamond-encrusted handle on this ergonomic trowel tells the world: I apartment
farm, I”m proud and I”m rich. ‘, ‘out of stock’, 7, 3, ‘trowel.jpg’, 0),
(24, ‘Bug Eradicator (Lavender scented)’, 19.95, ‘A small infestation is enough
to ruin your carefully manicured indoor garden. Bug Eradicator kills over 1000
species of invasive pests that threaten the well being of your apartment farm.
Keep out of reach of children; people of child-bearing age should avoid this
product; may be harmful to the elderly. Lavender scented.’, ‘in stock’, 2, 4,
‘none.gif’, 0),
(25, ‘Praying Mantis’, 399.95, ‘No pest”s prayers will be answered when the
praying mantis comes to your apartment. This powerful, ruthless, and loyal
companion will rid your indoor crops of all infestations. Recently featured in
the National Exasperator!’, ‘in stock’, 14, 4, ‘mantis.jpg’, 1),
(26, ‘Super Tomato Seed’, 69.50, ‘Why waste your time on thousands of little
cherry tomatoes, when only a single super tomato can feed a family of 10 for
three weeks. Pasta, anyone?’, ‘in stock’, 3, 2, ‘seeds,jpg’, 0),
(27, ‘Iceberg Lettuce Starts’, 4.95, ‘Even the titanic wouldn”t steer clear of
this delcious salad ingredient.’, ‘in stock’, 1, 1, ‘lettuce.jpg’, 0),
(28, ‘Leather Coveralls’, 386.95, ‘Inspired by the rugged look and feel of the
traditional, denim overall, these soft leather coveralls work hard at making
you look fine.’, ‘in stock’, 7, 5, ‘none.gif’, 0);
/*!40101 SET
CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
SEARCH_ENGINE.PHP
<?php
# FileName=”Connection_php_mysql.htm”
# Type=”MYSQL”
# HTTP=”true”
$hostname_search_engine = “localhost”;
$database_search_engine = “products”;
$username_search_engine = “root”;
$password_search_engine = “”;
$search_engine = mysql_pconnect($hostname_search_engine,
$username_search_engine, $password_search_engine) or
trigger_error(mysql_error(),E_USER_ERROR);
?>
HASIL AKHIR
FILE CARI.PHP
<?php
require_once(‘Connections/search_engine.php’); ?>
<?php
if (!function_exists(“GetSQLValueString”)) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = “”,
$theNotDefinedValue = “”)
{
if (PHP_VERSION < 6) {
$theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
}
$theValue =
function_exists(“mysql_real_escape_string”) ?
mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
switch
($theType) {
case “text”:
$theValue = ($theValue != “”) ? “‘” . $theValue . “‘” : “NULL”;
break;
case “long”:
case “int”:
$theValue = ($theValue != “”) ? intval($theValue) : “NULL”;
break;
case “double”:
$theValue = ($theValue != “”) ? doubleval($theValue) : “NULL”;
break;
case “date”:
$theValue = ($theValue != “”) ? “‘” . $theValue . “‘” : “NULL”;
break;
case “defined”:
$theValue = ($theValue != “”) ? $theDefinedValue : $theNotDefinedValue;
break;
}
return $theValue;
}
}
$currentPage
= $_SERVER["PHP_SELF"];
$maxRows_Recordset1
= 10;
$pageNum_Recordset1 = 0;
if (isset($_GET['pageNum_Recordset1'])) {
$pageNum_Recordset1 = $_GET['pageNum_Recordset1'];
}
$startRow_Recordset1 = $pageNum_Recordset1 * $maxRows_Recordset1;
$colname_Recordset1
= “-1″;
if (isset($_POST['cari'])) {
$colname_Recordset1 = $_POST['cari'];
}
mysql_select_db($database_search_engine, $search_engine);
$query_Recordset1 = sprintf(“SELECT * FROM products WHERE productName LIKE %s
ORDER BY productName ASC”, GetSQLValueString(“%” . $colname_Recordset1 . “%”,
“text”));
$query_limit_Recordset1 = sprintf(“%s LIMIT %d, %d”, $query_Recordset1,
$startRow_Recordset1, $maxRows_Recordset1);
$Recordset1 = mysql_query($query_limit_Recordset1, $search_engine) or
die(mysql_error());
$row_Recordset1 = mysql_fetch_assoc($Recordset1);
if
(isset($_GET['totalRows_Recordset1'])) {
$totalRows_Recordset1 = $_GET['totalRows_Recordset1'];
} else {
$all_Recordset1 = mysql_query($query_Recordset1);
$totalRows_Recordset1 = mysql_num_rows($all_Recordset1);
}
$totalPages_Recordset1 = ceil($totalRows_Recordset1/$maxRows_Recordset1)-1;
$queryString_Recordset1
= “”;
if (!empty($_SERVER['QUERY_STRING'])) {
$params = explode(“&”, $_SERVER['QUERY_STRING']);
$newParams = array();
foreach ($params as $param) {
if (stristr($param, “pageNum_Recordset1″) == false &&
stristr($param, “totalRows_Recordset1″) == false) {
array_push($newParams, $param);
}
}
if (count($newParams) != 0) {
$queryString_Recordset1 = “&” . htmlentities(implode(“&”, $newParams));
}
}
$queryString_Recordset1 = sprintf(“&totalRows_Recordset1=%d%s”,
$totalRows_Recordset1, $queryString_Recordset1);
?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
<title>Hasil Pencarian</title>
</head>
<body>
<h1>Hasil Pencarian….
</h1>
<?php do { ?>
<hr/>
<h3><?php echo $row_Recordset1['productName']; ?></h3>
<p><?php echo $row_Recordset1['description']; ?></p>
<hr/>
<?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?>
<table border=”0″>
<tr>
<td><?php if ($pageNum_Recordset1 > 0) { // Show if not first page
?>
<a href=”<?php printf(“%s?pageNum_Recordset1=%d%s”, $currentPage, 0,
$queryString_Recordset1); ?>”>First</a>
<?php } // Show if not first page ?></td>
<td><?php if ($pageNum_Recordset1 > 0) { // Show if not first page
?>
<a href=”<?php printf(“%s?pageNum_Recordset1=%d%s”, $currentPage, max(0,
$pageNum_Recordset1 – 1), $queryString_Recordset1);
?>”>Previous</a>
<?php } // Show if not first page ?></td>
<td><?php if ($pageNum_Recordset1 < $totalPages_Recordset1) { //
Show if not last page ?>
<a href=”<?php printf(“%s?pageNum_Recordset1=%d%s”, $currentPage,
min($totalPages_Recordset1, $pageNum_Recordset1 + 1), $queryString_Recordset1);
?>”>Next</a>
<?php } // Show if not last page ?></td>
<td><?php if ($pageNum_Recordset1 < $totalPages_Recordset1) { //
Show if not last page ?>
<a href=”<?php printf(“%s?pageNum_Recordset1=%d%s”, $currentPage,
$totalPages_Recordset1, $queryString_Recordset1); ?>”>Last</a>
<?php } // Show if not last page ?></td>
</tr>
</table>
</body>
</html>
<?php
mysql_free_result($Recordset1);
?>