Classes with Object

Pre-requisites: Basic Understanding of Programming Language, MySQL.


In this project:

  • We will create a class.
  • The class will be composed of different methods to access data.
  • These methods will be executed with the help of an object.

Type the following code in a PHP editor and save the file as UserClass.php in Classes folder of your root directory.

<?php
class User{
    		private $con;
    		public function connect($host, $user, $password, $database){
      		  	$this->con = mysqli_connect($host, $user, $password, $database);
        		if (mysqli_connect_errno()) {
            			echo "Connection Failed __".mysqli_connect_error();
            			exit();     
        		}	
    		}
    		public function getEmployeeData(){
        		$arr = $mainArr = array();
        		$sql = "SELECT a.first_name, a.last_name, a.email_id, b.name 
                    		FROM employees a 
                    		LEFT JOIN department b ON a.department_id = b.id 
                    		WHERE b.id IS NOT NULL";
        		$result = mysqli_query($this->con, $sql);
        		if($result){
            			while($row = mysqli_fetch_assoc($result)){
            		    		$arr['first_name'] = $row['first_name'];
                			$arr['last_name'] = $row['last_name'];
                			$arr['email_id'] = $row['email_id'];
                			$arr['name'] = $row['name'];
                			$mainArr[] = $arr;
            			}
        		}        
        		return $mainArr;
    		}    
}
$userObj = new User;
$userObj->connect("localhost", "root", "", "testing"); 
$employeeData = $userObj->getEmployeeData();
echo "<table border='1' cellpadding='5' cellspacing='0'>
                	<tr>
                   	<th>First Name</th>
                    	<th>Last Name</th>
                    	<th>Email ID</th>
                    	<th>Department</th>
                  </tr>";
if(is_array($employeeData) && count($employeeData) > 0){
    		
    		foreach($employeeData as $innerArr){
        		echo "<tr>";
        		foreach($innerArr as $key => $val){
            			echo "<td>".$val."</td>"; 
        		}
        		echo "</tr>";
    		}    		
}else{
    		echo "<tr>
            			<td colspan='4'>No records found</td>
        		</tr>";
}
echo "</table>";
?>

Run UserClass.php file in your browser to get the following output. URL may look like as follows:

Code Explanation of UserClass.php

1.

class User{

…     

}

Class keyword is used to declare a class followed by the classname.

2.

private $con;

 

Private access specifier is used to declare the class variable.

3.

public function connect($host, $user, $password, $database){

…   

}

 

Function connect() is defined to connect to a database using mysqli predefined methods.

4.

$this->con=mysqli_connect($host,$user,$password,$database);

 

 

$this operator is used to access the private member $con of the class.

5.

public function getEmployeeData(){

…

}

This function is defined to retrieve all the employee details from `employees` table.

6.

while($row = mysqli_fetch_assoc($result)){

     $arr['first_name'] = $row['first_name'];

     $arr['last_name'] = $row['last_name'];

     $arr['email_id'] = $row['email_id'];

     $arr['name'] = $row['name'];

     $mainArr[] = $arr;

}

 

Records are fetched using while loop and are stored in a main Array.

 

7.

$userObj = new User;

 

new keyword is used to create an object of the class. Syntax :

$Objectname = new Classname;

8.

$userObj->connect("localhost", "root", "", "testing"); 

$employeeData = $userObj->getEmployeeData();

Class methods are accessed with the help of created object using arrow operator.

9.

foreach($employeeData as $innerArr){

   echo "<tr>";

   foreach($innerArr as $key => $val){

      echo "<td>".$val."</td>"; 

   }

   echo "</tr>";

}

foreach loop has been used to print the data on the screen.


Summary

In this project, we have learned to create a Class, declaring variables, defining public member functions of the class, object creation and calling methods outside the class with the help of objects.

Two methods are taken where first method, connect() is defined to connect to a database and second method, getEmployeeData() is defined to retrieve the records from employees table along with their department name.

If records exist, it is printed on screen in the form of table. Otherwise, ‘No Records found’ message is printed.

Help Us to Improve our content

Let's Talk
Go back to Previous Course