Download presentation
Presentation is loading. Please wait.
Published byMarion Strickland Modified over 9 years ago
1
Database Handling Classes ISYS 475
2
Introduction to Classes A class is the blueprint for an object. –It describes a particular type of object. –It specifies the properties (fields) and methods a particular type of object can have. –One or more object can be created from the class. –Each object created from a class is called an instance of the class.
3
Adding a Class to a Project Right-click Source Files/New/PHP class –Assign a meaningful name. Steps: –Adding properties Property procedures: set / get Or declare Public variables –Adding methods
4
Class Code Example: Properties defined using Public variables <?php class emp { public $eid; public $ename; public $salary; public function empTax() { return $this->salary *.1; } ?>
5
Using the emp Class: 1. require it 2. Creating an instance of the class using new <?php require 'emp.php'; $myEmp = new emp(); $myEmp->eid='E1'; $myEmp->ename='Peter'; $myEmp->salary=5000.00; echo $myEmp->ename. ', your tax is: '. $myEmp->empTax(); ?>
6
Creating Property with Property Procedures Implementing a property with a public variable the property value cannot be validated by the class. We can create read-only, write-only, or write-once properties with property procedure. Steps: –Declaring a private class variable to hold the property value. –Writing a property procedure to provide the interface to the property value.
7
class Employee { private $eid; private $ename; private $salary; public function getEID() { return $this->eid; } public function setEID($value) { $this->eid = $value; } public function getEname() { return $this->ename; } public function setEname($value) { $this->ename = $value; } public function getSalary() { return $this->salary; } public function setSalary($value) { $this->salary= $value; } public function empTax(){ return $this->salary*.1; }
8
How the Property Procedure Works? When the program sets the property, the set property procedure is called and procedure code is executed. The value assigned to the property is passed in the value variable and is assigned to the hidden private variable. When the program reads the property, the get property procedure is called.
9
Using the Employee Class <?php require 'employee.php'; $myEmp2 = new employee(); $myEmp2->setEID("e2"); $myEmp2->setEname("Paul"); $myEmp2->setSalary(6500); echo $myEmp2->getEname(). ', your tax is: '. $myEmp2->empTax(); ?>
10
Anatomy of a Class Module Class Module Public Variables & Property Procedures Public Procedures & Functions Exposed Part Private Variables Private Procedures & Functions Hidden Part Private variables and procedures can be created for internal use. Encapsulation
11
Encapsulation is to hide the variables or something inside a class, preventing unauthorized parties to use. So methods like getter and setter access it and the other classes access it through property procedure.
12
Property Procedure Code Example: Enforcing a maximum value for salary public function setSalary($value) { if ($value > 150000) $this->salary=150000; else $this->salary= $value; }
13
Expand the Employee Class with a DateHire property and Compute Years Employed class Employee { private $eid; private $ename; private $salary; private $DateHire; private $yearsEmployed; public function getEID() { return $this->eid; } public function setEID($value) { $this->eid = $value; } public function getEname() { return $this->ename; } public function setEname($value) { $this->ename = $value; } public function getSalary() { return $this->salary; }
14
Continue public function setSalary($value) { if ($value > 150000) $this->salary=150000; else $this->salary= $value; } public function getDateHire(){ return $this->DateHire; } public function setDateHire($value){ $this->DateHire=$value; } public function getYearsEmployed(){ $hired = new DateTime($this->DateHire); $currentDate = new DateTime(); $interval= $hired->diff($currentDate); $this->yearsEmployed=$interval->format("a")/365.25; //$this->yearsEmployed=$currentDate->format("y")-$hired->format("y"); return $this->yearsEmployed; } public function empTax(){ return $this->salary*.1; }
15
Implementing a Read-Only Property: Declare the property with only the get procedure public function getYearsEmployed(){ $hired = new DateTime($this->DateHire); $currentDate = new DateTime(); $this->yearsEmployed=$currentDate->format("y")-$hired->format("y"); return $this->yearsEmployed; } Note 1: PHP Date format: http://php.net/manual/en/function.date.php Note 2: PHP DateInterval format: http://www.php.net/manual/en/dateinterval.format.php public function getYearsEmployed(){ $hired = new DateTime($this->DateHire); $currentDate = new DateTime(); $interval= $hired->diff($currentDate); $this->yearsEmployed=$interval->format("a")/365.25; return $this->yearsEmployed; }
16
Example of Using the Employee Class $myEmp2 = new employee(); $myEmp2->setEID("e2"); $myEmp2->setEname("Paul"); $myEmp2->setSalary(65000); $myEmp2->setDateHire("12/25/2005"); echo $myEmp2->getYearsEmployed(); echo $myEmp2->getEname(). ', your tax is: '. $myEmp2->empTax();
17
Inheritance The process in which a new class can be based on an existing class, and will inherit that class’s interface and behaviors. The original class is known as the base class, super class, or parent class. The inherited class is called a subclass, a derived class, or a child class.
18
Employee Super Class with Three SubClasses All employee subtypes will have emp nbr, name, address, and date-hired Each employee subtype will also have its own attributes
19
Inheritance Example class secretary extends employee{ private $WPM; public function getWPM() { return $this->WPM; } public function setWPM($value) { $this->WPM = $value; }
20
Method Override public function empTax(){ return $this->getSalary()*.15; } If we were to create a method in the child class having the same name, same number of parameters and the same access specifier as in it’s parent then we can say that we are doing method overriding. Example, add an empTax function with 15% tax rate to the secretrary class:
21
Database Handling Classes Data Source Database Classes Web Pages
22
Single-Record-Handling Classes –Retrieves a single record from the database and makes it available to your application in the form of an object. –The fields in the record are exposed as the object’s properties. –Any actions performed by the data (updates, calculations, etc.) are exposed as the object’s methods.
23
PHP List Assign variables as if they were an array Example: $info = array('coffee', 'brown', 'caffeine'); list($drink, $color, $power) = $info; echo "$drink is $color and $power makes it special.";
24
Single-Record-Handling Class Example class Customer { public $cid; public $cname; public $city; public $rating; public function getCustomerData($searchID){ $dsn = 'mysql:host=localhost;dbname=salesdb'; $username = 'root'; $password = ''; $db = new PDO($dsn, $username, $password); $query = "SELECT * FROM customers WHERE CID='". $searchID. "'"; $customers = $db->query($query); //$customer=$customers->fetch(); return list($this->cid, $this->cname, $this->city, $this->rating) = $customers->fetch(PDO::FETCH_NUM); } Note: the fetch method returns true/false, so the getCustomerData is a boolean function.
25
public function addNewCustomer(){ $dsn = 'mysql:host=localhost;dbname=salesdb'; $username = 'root'; $password = ''; $db = new PDO($dsn, $username, $password); $queryINS = "insert into customers value('". $this->cid. "','". $this- >cname. "','". $this->city. "','". $this->rating. "')"; return $db->exec($queryINS); } Adding a New Customer: Note: the exec method returns the number of records affected by the SQL statement and in this case returns 1 if insertion is successful.
26
Using the Customer Class to Add a New Customer CID: Cname: City: Rating:
27
Using the addNewCustomer PHP: require 'Customer.php'; <?php try { require 'Customer.php'; $myCust=new Customer(); $myCust->cid=$_POST["CID"]; $myCust->cname=$_POST["Cname"]; $myCust->city=$_POST["City"]; $myCust->rating=$_POST["Rating"]; if ($myCust->addNewCustomer()==1) echo "Adding succesful"; else echo "Adding not succesful"; } catch (Exception $e) { $error_message = $e->getMessage(); echo " Error message: $error_message "; } ?>
28
Using the Customer Class to Retrieve Data <?php try{ require 'Customer.php'; $myCust=new Customer(); $cid=$_GET["CID"]; if ($myCust->getCustomerData($cid)) echo $myCust->cname. $myCust->city. $myCust->rating; else echo "Record not exist"; } catch (Exception $e) { $error_message = $e->getMessage(); echo " Error message: $error_message "; } ?>
29
Other Methods Updating a record Deleting a record Note: CRUD –Create or add new entries – Read, retrieve, search, or view existing entries – Update or edit existing entries – Delete/deactivate existing entries
30
Modeling 1:M Relation with Classes Employee –EID –Ename –Dependents Department –DID –Dname –Employees Customer –CID –Cname –Orders
31
Arrays An array in PHP is actually an ordered map. A map is a type that associates values to keys. An array can be created using the array() language construct. It takes any number of comma-separated key => value pairs as arguments.
32
Declare and Access an Array Declare: array(key1 => value, key2 => value2, key3 => value3,... ) Example: $courseArray=array(); $courseArray["ISYS263"]="Introduction Information System"; $courseArray["ISYS363"]="Information Systems for Management"; $courseArray["ISYS350"]="Business Application Development"; Accessing an member by its key: echo $courseArray["ISYS363"];
33
Declare an array without key The key is optional. If it is not specified, PHP will use 0-based integer key. $courseArray=array(); $courseArray[0]="Introduction Information System"; $courseArray[1]="Information Systems for Management"; $courseArray[2]="Business Application Development"; echo $courseArray[1];
34
array_filter $data = array(42, “foo”, 96, “”, 100.96, “php”); // Filter each value of $data through the function is_numeric $numeric_data = array_filter($data, “is_numeric”); // Re-key the array so the keys are sequential and numeric (starting at 0) $numeric_data = array_values($numeric_data);
35
array_push: Push one or more elements onto the end of array Array ( [0] => orange [1] => banana [2] => apple [3] => raspberry ) <?php $stack = array("orange", "banana"); array_push($stack, "apple", "raspberry"); print_r($stack); ?>
36
array_pop — Pop the element off the end of array <?php $stack = array("orange", "banana", "apple", "raspberry"); $fruit = array_pop($stack); print_r($stack); ?> Array ( [0] => orange [1] => banana [2] => apple )
37
Remove an item from an array with unset command Use Index to Remove Array: $fruits = array("orange", "banana", "apple", "raspberry"); unset($fruits[2]); print_r($fruits); Result: Array ( [0] => orange [1] => banana [3] => raspberry ) Use specified key to delete array element: $fruits = array('fruit1' => "orange", 'fruit2' => "banana", 'fruit3' => "apple", 'fruit4' => "raspberry"); unset($fruits['fruit3']); print_r($fruits); Result: Array ( [fruit1] => orange [fruit2] => banana [fruit4] => raspberry )
38
Use array_values to reindex the array to fix the hole created by unset with index $fruits = array("orange", "banana", "apple", "raspberry"); unset($fruits[2]); $fruits=array_values($fruits); print_r($fruits); Result: Array ( [0] => orange [1] => banana [2] => raspberry )
39
Implementing a 1:M Relationship With Array CID Cname City Rating Orders --- an array of instances of order class Methods: GetOrders OID Odate SalesPerson Class Customer Class Order
40
Customer Class Properties public $cid; public $cname; public $city; public $rating; public $orders = array();
41
Order Class class Order { public $oid; public $cid; public $sid; public $odate; }
42
GetOrders Method public function getOrders($searchID){ $dsn = 'mysql:host=localhost;dbname=salesdb'; $username = 'root'; $password = ''; $db = new PDO($dsn, $username, $password); $query = "SELECT * FROM orders WHERE CID='". $searchID. "'"; $customers = $db->query($query); foreach ($customers as $row) { $order=new Order(); $order->oid=$row["oid"]; $order->cid=$row["cid"]; $order->sid=$row["sid"]; $order->odate=$row["odate"]; array_push($this->orders, $order); }
43
Example
44
<?php try{ require 'Customer.php'; require 'Order.php'; $myCust=new Customer(); $cid=$_GET["CID"]; if ($myCust->getCustomerData($cid)){ echo "Customer name: ". $myCust->cname. " "; echo "City: ". $myCust->city. " "; echo "Rating: ". $myCust->rating. " "; $myCust->getOrders($cid); echo " ". " OID ". " CID ". " SID ". " Odate "; $length=count($myCust->orders); for ($i=0;$i<$length;++$i){ $oid=$myCust->orders[$i]->oid; $cid=$myCust->orders[$i]->cid; $sid=$myCust->orders[$i]->sid; $odate=$myCust->orders[$i]->odate; echo " $oid ". " $cid ". " $sid ". " $odate "; } echo " "; } else echo "Record not exist"; } catch (Exception $e) { $error_message = $e->getMessage(); echo " Error message: $error_message "; } ?>
45
A page with data from 4 tables: Customers, Orders, Details, Products
46
Customer Class public $cid; public $cname; public $city; public $rating; public $orders = array(); Methods: getCustomerData getOrders
47
Order Class: class Order { public $oid; public $cid; public $sid; public $odate; public $details=array();
48
getDetails method public function getDetails($searchID){ $dsn = 'mysql:host=localhost;dbname=salesdb'; $username = 'root'; $password = ''; $db = new PDO($dsn, $username, $password); $query = "SELECT * FROM orderdetail WHERE OID='". $searchID. "'"; $details = $db->query($query); foreach ($details as $row) { $detail=new OrderDetail(); $detail->oid=$row["oid"]; $detail->pid=$row["pid"]; $detail->pname=$row["pname"]; $detail->qty=$row["qty"]; $detail->price=$row["price"]; $detail->amount=$row["amount"]; array_push($this->details, $detail); }
49
OrderDetail class: class OrderDetail { public $oid; public $pid; public $pname; public $qty; public $price; public $amount; }
50
MySQL View Create view orderdetail as Select oid, pid,pname,qty,price,qty*price as amount From products natural join odetails; Use the view as a table: $query = "SELECT * FROM orderdetail WHERE OID='". $searchID. "'";
51
PHP using the classes <?php require 'Customer.php'; require 'Order.php'; require 'OrderDetail.php'; $mycust=new Customer(); $mycust->getCustomerData('C1'); $mycust->getOrders('C1'); echo "CID: $mycust->cid Name: $mycust->cname City: $mycust->city Rating: $mycust->rating "; echo " ". " OID ". " CID ". " Odate ". " SID "; foreach ($mycust->orders as $order) { $oid=$order->oid; $cid=$order->cid; $odate=$order->odate; $sid=$order->sid; $order->getDetails($oid); echo " $oid ". " $cid ". " $odate ". " $sid "; echo " Details:OID ". " PID ". " PNAME ". " QTY ". " PRICE ". " AMOUNT ". " "; foreach ($order->details as $detail) { $oid=$detail->oid; $pid=$detail->pid; $pname=$detail->pname; $qty=$detail->qty; $price=$detail->price; $amount=$detail->amount; echo " $oid ". " $pid ". " $pname ". " $qty ". " $price ". " $amount ". " "; } echo " "; ?>
52
Entity Class Generator: NetBeans PHP Database Class Plugin Db2php: – http://code.google.com/p/db2php/ http://code.google.com/p/db2php/ – Or: – http://plugins.netbeans.org/plugin/41522/db2php http://plugins.netbeans.org/plugin/41522/db2php – File name: db2phpnb-1.107.nbm – Save as:
53
Add the plugIn NetBeans: – Tools/PlugIns/Downloaded/Add PlugIns
54
Using the db2php plugin Sources File/New/Other/PHP Entity Class from Database
55
Example of using the class http://code.google.com/p/db2php/wiki/HOWTO interface Db2PhpEntity: – http://code.google.com/p/db2php/source/browse/db 2phplib/src/main/resources/org/afraid/poison/db2ph p/generator/utility/Db2PhpEntity.class.php?r=9c94749 37cae0d2dc73ee55aafde0897c58bf2bf http://code.google.com/p/db2php/source/browse/db 2phplib/src/main/resources/org/afraid/poison/db2ph p/generator/utility/Db2PhpEntity.class.php?r=9c94749 37cae0d2dc73ee55aafde0897c58bf2bf abstract class Db2PhpEntityBase implements Db2PhpEntity: – http://code.google.com/p/db2php/source/browse/db 2phplib/src/main/resources/org/afraid/poison/db2ph p/generator/utility/Db2PhpEntityBase.class.php?r=313 5161710d01bfabf9a5add0d1ddc6098766137
56
Using the Class <?php include 'db2phpclass.php'; require 'CustomersModel.class.php'; $db= new PDO('mysql:host=localhost;dbname=salesdb', 'root', ''); $customer = new CustomersModel(); $sql="select * from customers where cid='C1'"; $results=$customer->findBySql($db, $sql); echo var_dump($results); echo $results[0]->getCname(); ?>
57
PEAR - PHP Extension and Application Repository Home Page: – http://pear.php.net/index.php http://pear.php.net/index.php PEAR is a framework and distribution system for reusable PHP components.
58
DB_Table http://pear.php.net/manual/en/package.data base.db-table.php
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.