PHP dapat mengolah data dari suatu database dengan mudah dan cepat. Secara garis besar, ada dua hal yang perlu dipahami yaitu bahasa SQL (Structured Query Language) yang merupakan bahasa standar dalam mengolah database dan fungsi-fungsi yang disediakan PHP dalam mengakses database. Kasus pengolahan database yang dibahas dalam modul ini adalah Buku Tamu.
3.1 Membuat Database
Saat ini membuat database MySQL tidak perlu menggunakan cara manual (yaitu menjalankan file mysql.exe), karena sekarang sudah banyak tool visual yang membantu anda membuat database dengan mudah dan cepat. Salah satunya adalah tool phpMyAdmin yang berbasis web. Langkah-langkah penggunaan phpMyAdmin sebagai berikut:
1. Buka browser dan ketikkan alamat http://localhost/phpmyadmin, maka akan tampil halaman depan dari phpMyAdmin
Gambar 1.4 Halaman depan phpMyAdmin
2. Untuk membuat database, isikan nama database yang akan dibuat pada bagian Create new database, lalu klik tombol Create. Pada langkah ini, masukkan nama database ‘bukutamu’.
3. Maka akan terbentuk sebuah database dengan nama ‘bukutamu’.
Gambar 1.5 Halaman database ‘bukutamu’
4. Untuk membuat tabel baru, masukkan nama tabel pada Name dan jumlah kolom data pada Fields. Pada langkah ini, masukkan nama tabel ‘tamu’ dan jumlah field 4, lalu klik tombol Go.
Gambar 1.6 Halaman entri field dan atribut tabel ‘tamu’
5. Masukkan entri field dan atribut di bawah ini, yaitu:
a. Field: no, Type: INT, Extra: auto_increment, Primary v
b. Field: nama, Type: VARCHAR 20
c. Field: email, Type: VARCHAR 20
d. Field: pesan, Type: TEXT
6. Setelah selesai, klik tombol Save, maka akan terbentuk tabel ‘tamu’.
Gambar 1.7 Halaman tabel ‘tamu’
3.2 Koneksi PHP ke Database
Untuk bisa mengakses database dan tabel di MySQL, kita harus melakukan koneksi terlebih dahulu.
Skrip koneksi.php
mysql_connect(“localhost”, “root”, “”);
mysql_select_db(“bukutamu”);
?>
Keterangan koneksi.php
mysql_connect(“hostname”, “username”, “password”);
Untuk melakukan koneksi ke server database MySQL.
mysql_select_db(“databasename”);
Untuk memilih sebuah database di dalam server database MySQL.
File koneksi.php ini akan disisipkan ke dalam file .php lainnya, karena setiap kali mengolah data di database, maka kita harus melakukan koneksi terlebih dahulu. Untuk menyisipkan, cukup tuliskan:
include(“filename”);
3.3 Input Data
Proses input data adalah suatu proses untuk memasukkan data ke dalam tabel. Perintah SQL yang akan digunakan adalah:
INSERT INTO tablename (field1, field2, …) VALUES (data1, data2, …)
Skrip form_tamu.php
INPUT BUKU TAMU
Skrip update_tamu.php
include “koneksi.php”;
$sql = “UPDATE tamu SET nama=’$nama’, email=’$email’, pesan=’$pesan’
WHERE no=’$id’”
$hasil = mysql_query($sql);
if ($hasil) {
header(“location:tampil_tamu_admin.php”);
} else {
echo “Proses update data gagal”;
}
?>
3.9 Delete Data
Proses delete data adalah suatu proses untuk menghapus data yang ada dalam tabel. Untuk dapat menghapus data, kita menggunakan perintah SQL berikut:
DELETE FROM tablename WHERE keyfield=’$id’;
Skrip delete_tamu.php
include “koneksi.php”;
$sql = “DELETE FROM tamu WHERE no=’$id’”
$hasil = mysql_query($sql);
if ($hasil) {
header(“location:tampil_tamu_admin.php”);
} else {
echo “Proses delete data gagal”;
}
?>
3.10 Search Data
Proses search data adalah suatu proses untuk menemukan data yang ada dalam tabel berdasarkan kriteria tertentu. Untuk dapat menemukan data, kita menggunakan perintah SQL berikut:
SELECT * FROM tablename WHERE field LIKE ’%$id%’;
Perintah SQL di atas dapat berbeda tergantung pada sintaks yang digunakan. Pencarian di atas bertujuan untuk menemukan data yang mengandung kata yang dicari, misalnya pencarian dengan id ‘udi’ akan memberikan hasil ‘budi’, ‘udik’, dan ‘mudik’.
Skrip form_cari.php
PENCARIAN DATA TAMU
Skrip cari_tamu.php
include “koneksi.php”;
echo “
HASIL PENCARIAN DATA
”;$sql = “SELECT * FROM tamu WHERE nama LIKE ‘%$nama%’”;
$hasil = mysql_query($sql);
$total = mysql_num_rows($hasil);
if ($total) {
echo “Tamu dengan nama $nama ada: $jumlah orang
”;
echo “
Nama | Pesan | |
---|---|---|
$data[nama] | ”;$data[email] | ”;$data[pesan] |
} else {
echo “Tamu dengan nama $nama tidak ada”;
}
?>
Catatan: Uji skrip terlebih dahulu. Perhatikan mengenai $_POST terhadap GLOBAL VARIABLES.
4. Dasar-dasar Pemrograman Berbasis Obyek
Dalam modul ini, kita akan mempelajari 3 hal, yaitu:
1. Fungsi include()
2. PHP Classes
3. Object-Oriented Programming and Inheritance
4.1 Fungsi Include()
PHP memiliki fungsi include() yang digunakan untuk menggabungkan kode dari sebuah file ke kode pada file lainnya. Hal ini sangat bermanfaat dalam pengerjaan yang melibatkan halaman web dalam jumlah banyak. Misalkan, kita menggunakan template HTML untuk menstandarisasi tampilan halaman web, sehingga dapat menghemat waktu dalam pengerjaan dan mengurangi redundansi kode. Template HTML dapat digunakan pada setiap halaman dengan menggunakan fungsi include().
For instance, if you have a standard heading for all pages on a site you can create a document named header.inc like the following:
echo '';
echo '
echo '';
echo 'Bob's Towing Yard ';
?>
header.inc sets the title of the page to "Bob's" and begins the body content of the page with "Bob's Towing Yard" and Bob's logo (bobs_logo.jpg). You then include this code by calling the function include() in the appropriate section of your PHP page. We'll call the page index.php:
include(header.inc);
?>
After you call the include() function you can add any unique content you desire. Viola, you have header uniformity across any page that includes header.inc. Of course, it isn't a stretch to see that this can also be applied to uniform sections such as the footer of a web page, navigation menus, side panels, etc.
This immediately makes each page a 6-10 line project instead of a 20-40 line project. Once you have the included elements all dialed in, the only part of a web page you have to update is the content that is unique to the situation. In addition, if you need to change something miniscule, like Bob's logo, or even the name Bob, the only place you have to make the change is in header.inc. All of the pages using header.inc will be automatically updated.
Note: It bears mentioning that the extension .inc is primarily used to differentiate include files from .php files. When looking at a directory of files it can be a bit daunting to pick out which files are merely include files and which are valid PHP pages. There is a difference in how browsers read these files however, and that difference should be kept in mind when creating a webpage. .inc files are treated as plain text and are therefore sent through the browser as plain text. If you view source on a page using .inc files, you will see the contents of these files. If the information contained in the .inc file is sensitive (i.e. passwords, personal information) it is best to use the .php extension so that the information is not readily available. You can also save .inc files outside of the directory, but I have always preferred to keep information that I want to be invisible under the .php extension. Files using the .php extension are treated exactly the same when called by the include() function:
include(header.inc)
and
include('header.php')
will give you the same results.
If you are using an Apache server, you can also manipulate the server configuration so that a user may not access .inc files.
Now, on to Classes.
Classes in Session
Now we know that we can feed whatever redundant elements we like into any number of pages by simply invoking a single function, let's take it a step further and introduce classes.
Classes start using the Object-Oriented Programming (OOP) methodology in PHP (OOP is only available in PHP versions 4.0 and later). Briefly, OOP uses objects, which are unique and identifiable collections of stored data and operations that operate on that data. These objects are not unlike real-life objects, such as a chair, or a table. An object can also be a navigation menu, a button, a text field or a style sheet. Objects can further be grouped into classes. Classes are collections of objects that share certain criteria but may vary from object to object. For example, using horses as a class, certain criteria are necessary for an object to be classified as a horse: four legs, hooves, mane. However, many aspects of these criteria can have different values: black mane, brown mane, white mane, and so on.
This is the basic structure of a class:
class classname
{
}
To create a class in PHP, we begin with the keyword class, and the classname will follow. Next we will create attributes and operations for our class and place them between the brackets. Attributes are declared as follows:
class classname
{
var $attribute1;
var $attribute2;
}
Operations are created by declaring functions within the class definition:
class classname
{
function operation1()
function operation2($param1, $param2)
}
The function operation1 takes no parameters, while operation2 takes two parameters (param1, param2).
Most classes will have a special operation called a constructor. A constructor is called as soon as an object is created and serves the purpose of setting reasonable values for attributes or creating other objects needed by the parent object. A constructor is called in the same way a class is called, but it shares the name of the class. A constructor can be called manually, but its main purpose is to be called automatically when an object is created. This is the structure of a class that uses a constructor:
class classname
{
function classname($param)
{
echo "The Constructor will be called with the
parameter $param";
}
}
Now that we have declared a class, we need to create an object that belongs to that class. This is also called instantiation, creating an instance of the class. So we'll declare a class, give it a constructor, and then create two objects. The object is created using the keyword new:
class classname
{
function classname($param)
{
echo "The Constructor will be called with the
parameter $param";
}
}
$x = new classname('Ego');
$y = new classname('Sum');
Our constructor is called by both objects, so the output will look like this:
The Constructor will be called with the parameter Ego
The Constructor will be called with the parameter Sum
Now that we have the basic structure of a PHP class down, let's look at adding attributes and operations to the mix.
Attributes and Operations
Earlier, when we discussed the nature of objects we compared them to horses. In order to qualify as a "horse" an object must meet certain criteria such as four legs, hooves, mane. These are our object's attributes. Without these atributes nothing will differentiate a "horse" from a "lizard". Thank you Captain Obvious, no one will ever mistake a horse for a lizard! That is true, but it's very easy to mix up a "home" button that takes a user to index.php and a "home" button that takes them to my_personal_index.php. While both buttons may look identical to the user, their individual purposes are quite different, and thus their individual attributes make all the difference in the world.
Variables allow us to keep elements our of code dynamic by replacing static values with values that change according to user intervention. Attributes are no different, and as such can be written to change fluidly as the user interacts with the page.
Within a class, you have access to a special variable called $this. If you have an attribute called $decide, you refer to it as $this->decide when you are setting the attribute from an operation within the class. For example:
class classname
{
var $decide;
function form($param)
{
$this->decide = $param;
echo $this->decide;
}
}
This class declares a variable $decide, then uses the operation form (which is passed the parameter $param) to set the parameter to $decide. Written in code-speak, the class looks like so: $this->decide = $param. Fianlly, it accesses the attribute by printing it: echo $this->decide.
Operations are called in the same way attributes are called. First we declare our class:
class classname
{
function form1()
{
}
function form2($param1, $param2)
{
}
}
Then create an object:
$z = new classname();
Finally, we call the operations in the same way we call other functions, by name. However, because these operations belong to an object rather than a normal function, we must identify the object to which they pertain. We use the object's name in the same way as the object's attributes:
$z->form1();
$z->form2(2, 3);
If our operations return values we can retrieve them as variables like so:
$a = $z->form1();
$b = $z->form2(2, 3);
Still with me? All of this is pretty simple, mostly thanks to PHP's logical nature. Pretty soon, we'll see how complete classes can be used to load major elements of a page. First, let's see how classes inherit attributes and operations from the classes above them.
No, this lesson is not about to turn into a lecture on Marxism. I promise.
Inheritance
Inheritance is what makes using classes more robust than simply using an include file. With inheritance, we can create a hierarchal relationship between classes and subclasses. A subclass inherits attributes and operations from its superclass, (the class above it in the hierarchy). Once again, we can save time and effort by writing a base superclass instead of spreading redundant operations over several classes. This base can then be inherited by subclasses and refined to meet even more specialized criteria.
To implement inheritance in PHP we use the keyword extends. For instance, the statement "class B extends class A" creates a Class B that inherits from Class A.
So if we have these classes:
class A
{
var $decide1;
function form1()
{
}
}
class B extends A
{
var $decide2;
function form2()
{
}
}
The following are valid accesses of operations and attributes from an object of type "B":
$b = new B();
$b->form1();
$b->form2();
$b->decide1 = x;
$b->decide2 = y;
In addition, the following are valid for an object of the type "A":
$a = new A();
$a->form1();
$a->decide1 = x;
However, inheritance only works one-way, so the following:
$a->form2();
$a->decide2 = y;
are not valid because form2() and $decide2 were created in class B. Class A does not inherit from Class B. This inheritance dynamic is also used to override values. For instance, if we declare a class A and class B again:
class A
{
var $y = 'the first value';
function form1()
{
echo "Our variable is $this->y";
}
}
class B extends A
{
var $y = 'the new value';
function form1()
{
echo "Our variable is $this->y";
}
}
class A is unaffected by declaring class B. The following is still the output of declaring Class A and creating an object of type A:
$a = new A();
$a->form1();
The above declaration will return:
Our variable is the first value
If we create an object of type B, like this:
$b = new B();
$b->form1();
it will return:
Our variable is the new value
Enough talk, let's do something with our classes!
Classes Put Into Action
Now, with your knowledge of classes and of the include() function, you can start setting up pages which contain objects that reference classes contained in included files. It all sounds a little complicated, but trust me. You'll thank me shortly.
Let's begin by creating a simple navigation menu to display on all of our site's pages. We'll name this document mainmenu.inc:
class mainmenu
{
function mainmenu()
{
echo '
echo '
href="home.php">HOME
echo '
href="services.php">SERVICES
echo '
href="portfolio.php">PORTFOLIO
echo '
href="contact.php">CONTACT
echo '';
}
}
?>
We have created a class named mainmenu, we have also created a constructor named mainmenu so that when an object of the mainmenu type is created, it will perform the code within the class. The code within the function mainmenu is a pretty straightforward horizontal menu. There are different methods for producing this effect, such as storing the button names and URLs as a variable array, but we'll keep it simple for the sake of introduction and let you go wild on it when you put it into practice.
Let's create one more class before we create the page, shall we? Let's tackle a stylesheet. We'll call this styles.inc:
class stylesMainMenu
{
function stylesMainMenu()
{
?>
}
}
?>
Notice that ?> precedes the actual stylesheet, and tag. This escapes from PHP so that the content will be read as HTML and treated accordingly. Just remember that you must return to PHP to close the function and also close the class.
Alright, now comes the fun part. Let's create index.php which will contain a menu that is formatted by our stylesheet:
include('mainmenu.inc');
include('styles.inc');
$page = new mainmenu();
$page = new stylesMainMenu();
?>
That's it.
No, really, that's it! We included mainmenu.inc and styles.inc, these provide us with the code for the menu and for our stylesheet. We then created a new object named $page by calling our constructors from within the mainmenu and stylesMainMenu classes. Objects do not always need to share their name ($page in this case), however, in order for the stylesheet to apply to the menu they need the same name.
You can make this operation as complicated or as simple as you like. In this example, we separated the classes into two files, mainmenu.inc and styles.inc, but they can both be stored in the same .inc files if you prefer. Furthermore, you can keep an entire library of stylesheets in a file called styles.inc. By making each stylesheet its own class, you can call on the attributes from that stylesheet simply by calling on its classname or contructor and including styles.inc. The same pertains to libraries of functions as well as redundant page elements such as menus, picture displays and information bars.
You can also make the menu itself dynamic by manipulating the operations within the mainmenu class. Treat these operations as instructed on page three of this lesson, and write them to conform to specific parameters and situations. For instance, you can create a conditional menu. Write the mainmenu operation so that if you are on index.php all of the buttons leading to the pages will be present in the menu, but if you are on services page, all buttons will be available except "services,” if you are on the portfolio page all buttons will be available except "portfolio", and so on. Or perhaps you would like a different background for the menu depending on the page.
As you can see, the sky's the limit when you're using "hidden" PHP classes. Go have fun with it!
Sports Betting at Safest Betting Sites in Israel - Airjordan10 RetroOutlet
BalasHapusSafest find air jordan 18 retro racer blue Betting Sites in Israel air jordan 18 retro yellow shipping · The Best and Best Betting Sites in the UK · The UK's Hottest Bookmakers air jordan 18 retro toro mens sneakers shop · Betfair how can i order air jordan 18 retro Sports Betting Authority 온라인바카라 · Betfair