Data retrieving in object oriented php programming
The object model was rewritten to allow for better performance and more features. This was a major change from PHP 4. PHP 5 has a full object model.
This Tutorial start with the employee table you created in my_database.create table employee.
CREATE TABLE IF NOT EXISTS `employee` ( `id` int(40) NOT NULL AUTO_INCREMENT, `division` varchar(40) NOT NULL, `name` varchar(40) NOT NULL, `appointed` varchar(40) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ; -- -- Dumping data for table `employee` -- INSERT INTO `employee` (`id`, `division`, `name`, `appointed`) VALUES (1, 'Production', 'Jhones', '1965'), (2, 'Service', 'Taylor', '1970'), (3, 'Marketting', 'Bayker', '1980'), (4, 'Human resource', 'Steven', '1988'), (5, 'Production', 'Jennifer', '1990'), (6, 'Service', 'Lopez', '2000'), (7, 'Marketting', 'Bayker', '2000'), (8, 'Marketting', 'Bayker', '2010'), (9, 'Human resource', 'Steven', '2008'); |
Then by using class and functions you can retrieve the data using below scripts
<table border=1 align="center"><tr> <th>ID</th><th>Division</th><th>Name</th><th>Appointed Year</th></tr> <?php class MySQL { private $host; private $username; private $password; private $database; private $conn; public function __Construct($set_host, $set_username, $set_password){ $this->host = $set_host; $this->username = $set_username; $this->password = $set_password; $this->conn = mysql_connect($this->host, $this->username, $this->password) or die("Couldn't connect"); } public function Database($set_database) { $this->database=$set_database; mysql_select_db($this->database, $this->conn) or die("cannot select Dataabase"); } public function Fetch($table_name){ return mysql_query("SELECT * FROM ".$table_name, $this->conn); } } $connect = new MySQL('localhost','root',''); $connect->Database('my_database'); $posts = $connect->Fetch('employee'); if ($posts && mysql_num_rows($posts) > 0) { echo "<center>Table Employee:</center><BR>"; while ($record = mysql_fetch_array($posts)) { echo "<tr><td>".$record[0]."</td>"; echo "<td>".$record[1]."</td>"; echo "<td>".$record[2]."</td>"; echo "<td>".$record[3]."</td>"; echo "</tr>"; } } else { echo "No Records Found!"; } echo "</table>"; ?> |
Retrieved table look like bellow
ID | Division | Name | Appointed Year |
---|---|---|---|
1 | Production | Jhones | 1965 |
2 | Service | Taylor | 1970 |
3 | Marketting | Bayker | 1980 |
4 | Human resource | Steven | 1988 |
5 | Production | Jennifer | 1990 |
6 | Service | Lopez | 2000 |
7 | Marketting | Bayker | 2000 |
8 | Marketting | Bayker | 2010 |
9 | Human resource | Steven | 2008 |
No comments:
Post a Comment