Primary Key & Foreign Key Implementation: MySQL

This video tutorial illustrates the implementation of Primary key and Foreign key, using MySQL.

You can run the same commands / Queries shown in the video on both phpmyadmin as well as on MySQL console.

You can also look at: Primary Foreign Unique Keys, AUTO_INCREMENT: MySQL

student-enrol-database-tables-structure

Primary Key
The PRIMARY KEY constraint uniquely identifies each record in a database table.
Primary keys have unique values.
Primary Keys are NOT NULL by default.

Creating student table:

1
2
3
4
5
6
CREATE TABLE student(
 stud_id  int AUTO_INCREMENT,
 name     varchar(30) NOT NULL,
 age      int NOT NULL,
 PRIMARY KEY(stud_id)
);

Foreign Key
A FOREIGN KEY in one table points to a PRIMARY KEY in another table.

Creating enrol table:

1
2
3
4
5
6
CREATE TABLE enrol(
 rol_no  int AUTO_INCREMENT,
 stud_id int NOT NULL,
 PRIMARY KEY(rol_no),
 FOREIGN KEY(stud_id) REFERENCES student(stud_id)
);

student-enrol-database-tables

Primary Key & Foreign Key Implementation: MySQL


You need to a flashplayer enabled browser to view this YouTube video

YouTube Link: http://www.youtube.com/watch?v=eTK9TLciRpU [Watch the Video In Full Screen.]



Note:
1. You can have only 1 primary key per table. But can have zero or more foreign keys in a table.
2. You can not delete primary key row directly, without deleting all the rows referring to that row.

DBMS Basics: Getting Started Guide

Getting started with Database Management System.

In this video tutorial we’re trying our best to keep everything to the minimum, and make sure not to make it look complicated for beginners.

The tables and the normalization shown in the video are just for the purpose of demonstration.

dbms-basics

DBMS is a software system which helps in managing incoming data, organizes it and provides certain ways for the data to be modified and/or extracted by the users or other programs.

Some examples of Database Management System Software include MySQL, PostgreSQL, Microsoft Access, SQL Server, FileMaker, Oracle, RDBMS, dBASE, Clipper, and FoxPro.
Also: Some Native database systems that can be connected with PHP ?

Tables Relational databases are made up of relations, commonly known as TABLES.
Relationships exists between the tables and the data are inter-related by making use of Primary and Foreign keys.

Table Columns
It has unique names.
Each column has an associated datatype.
Columns are sometimes called as fields or attributes.

Table Rows
Each row in the table represents individual data.
Rows are also called as records or tuples.

Values
Every value must have the same data type, as specified by it’s column.

Key
To identify each row uniquely.
The identifying column in a table is called as key or primary key.

Schema
Complete set of table design for a database.
It’s like a blueprint for the database.

A Schema should show the tables along with their columns, and the primary and foreign keys. Usually primary key’s are underlines and foreign keys are italicized.

Database Management System: Basics


You need to a flashplayer enabled browser to view this YouTube video

YouTube Link: http://www.youtube.com/watch?v=aR44FbeeFH8 [Watch the Video In Full Screen.]



Anomalies
Assume that we’re running an online store.
We’ve a order table.

If a person called Satish orders Apple iPad, Mac Book and a iPhone from our site.
We store his name and address and quantity of his order.

Next, Satish moves to a different place before we process the order, now we will need to update his address at 3 places!

Doing 3 times as much work. We may miss updating Satish’s address in some place, making the data inconsistent. This is called modification anomaly.

If we design our database table in this way, we’ll need to take the address of Satish each time he orders something from our online store. This way, we need to always make sure the address(data) is consistent across all the rows. If we do not take care, we may end up with conflicting data.
Ex: One row may indicate Satish to be living in Bangalore and another row may indicated Satish to be living in New York!
This scenario is called Insertion anomaly.

Once all the orders of Satish has been processed, we delete the records. This way, we no longer have Satish’s address. So we can’t send any promotional offers etc to Satish in the future. If he want’s to order something again from our online store, he need to enter his address again. This scenario is called deletion anomaly.

We could solve these anomaly problems by making use of Primary and Foreign key’s and by developing the skill/art of normalization.

Database normalization is the process of organizing the fields and tables of a relational database to minimize redundancy and dependency. Normalization usually involves dividing large tables into smaller (and less redundant) tables and defining relationships between them. The objective is to isolate data so that additions, deletions, and modifications of a field can be made in just one table and then propagated through the rest of the database using the defined relationships.

Primary Key
The PRIMARY KEY constraint uniquely identifies each record in a database table.
Primary keys must contain unique values.
A primary key column cannot contain NULL values.
Each table should have a primary key, and each table can have only ONE primary key.

Foreign Key
A foreign key is a field in a relational table that matches a candidate key of another table. The foreign key can be used to cross-reference tables.

Relationships
We’ll cover
one-one
one-many
many-many
relationships in coming video tutorials, with some real time examples.

Per-Class Constants And Static Methods: PHP OOP

This video tutorial illustrates the concepts of Per-Class Constants and Static Methods in Object Oriented PHP. Per-Class Constants was introduced in PHP5.

Per-Class Constants
Unlike variables, constants doesn’t change/alter its value during the program execution.
They’re treated as fixed values. Something which doesn’t change in the course of execution.

Since its value remains constant for all the objects, there is no need of an object to be created in-order to access it. We can directly access it using the class name and :: operator and the constant name.

Per-Class Constant
Math.php

1
2
3
4
5
6
7
< ?php
	class Math {
		const pi = 3.14159;
	}
 
       echo Math::pi;
?>

This would output, 3.14159

Static Method
There’re situations where we need to take something which is global to the class.
And there is no use of invoking the method for all objects of that class. In such a situation make use of static methods. This way, you need not instantiate the class to invoke the method.

Syntax to invoke static method: class name, :: operator, method name.

Static Method Invocation
Math.php

1
2
3
4
5
6
7
8
9
< ?php
	class Math {
		static function square($no)
		{
			echo "<br />".$no * $no;
		}
                echo Math::square(10);
	}
?>

This would output, 100

Per-Class Constants And Static Methods: PHP OOP


You need to a flashplayer enabled browser to view this YouTube video

YouTube Link: http://www.youtube.com/watch?v=0tpX377CEgw [Watch the Video In Full Screen.]



For example,
Declare database connection method as static, so that you can directly use the class name instead of creating an instance of the class.
This way, you can connect to the database, but you don’t have access to other non-static methods of the same class!

Implementing Interfaces: PHP OOP

Video tutorial illustrates the concept of implementing interfaces in Object Oriented PHP.

We also show you, how it over comes the ambiguity issue of multiple inheritance.

Interfaces acts as placeholder or the blueprint for what you can create.
Interfaces provide the basic design for a class with zero implementation detail.
Interfaces define what methods a class must have ..and you can create other methods outside of these limitations too.

extend and implement
interface.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
< ?php
		class A
		{
			public function display()
			{
				echo "I love Apple Products";
			}
		}
 
		interface I
		{
			const COMPANY = "Technotip.com";
			public function company();
			public function display();
		}
 
		class B extends A implements I
		{
			function company()
			{
				echo "I Love BuySellAds and Technotip.com";
			}
 
			function display()
			{
				echo "Microsoft & Oracle";
			}
		}
 
		$obj = new B();
		$obj->company();
?>

This would output I Love BuySellAds and Technotip.com

Accessing Constant Variable
To access the constant variable present inside interface, use the class name followed by scope resolution operator and then the constant variable name:
B::COMPANY

Implementing Interfaces: PHP OOP


You need to a flashplayer enabled browser to view this YouTube video

YouTube Link: http://www.youtube.com/watch?v=iOfpmXph5EU [Watch the Video In Full Screen.]



In multiple inheritance you have two parent classes. If both of them have a method with same name, signature and you don’t even override it in the child / derived class, then PHP engine will have no way to know which method to use.

multiple-inheritance-classB-classC-to-classA


In interface, you HAVE TO (must) override the methods present in interface class while implementing it. Hence solving the ambiguity issue.

Note:
All methods declared in an interface must be public.
All variables in interface must be constant.
Interfaces cannot be instantiated.
Object Oriented PHP only supports Single Inheritance. i.e., you can have only one parent class.
You can implement more than one interface. Use comma separation to implement more than one interfaces.

Ex 1:
interface A { }
interface B { }
class C implements A, B { }

Ex 2:
class D { }
interface A { }
interface B { }
class C extends D implements A, B { }

Multiple And Hybrid Inheritance: PHP OOP

Video tutorial to illustrate Inheritance mechanism in Object Oriented PHP.

Inheritance is a mechanism where objects of one class acquires the properties of objects of another class.

PHP supports only single inheritance.
i.e., a class should inherit from only one parent class / base class. If it inherits from more than one base class, then it’s not a valid inheritance in PHP.

Thus, multiple inheritance and hybrid inheritance is not supported in Object Oriented PHP.

Single Inheritance
class B inherits from class A

single-inheritance-classA-to-classB

class C inherits from class B which in turn inherits from class A

single-inheritance-classA-to-classB-to-classC

class B and class C inherits from class A

single-inheritance-classA-to-classB-and-classC

Invalid Inheritance in PHP
Multiple Inheritance
class A inherits from two base/parent classes B and C

multiple-inheritance-classB-classC-to-classA

Hybrid Inheritance
class B and C inherits from a single base/parent class, i.e., class A
again, class D inherits from class B and class C

hybrid-inheritance

Single Inheritance: class B and class C inherits from class A

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
< ?php
		class A
		{
			function display()
			{
				echo "Apple, Google, Oracle, Microsoft";
			}
		}
 
		class B extends A
		{
 
		}
 
		class C extends A
		{
 
		}
 
		$obj = new C(); 
//		$obj = new A(); 
//		$obj = new B(); 
		$obj->display();
?>

This should output
Apple, Google, Oracle, Microsoft

Multiple And Hybrid Inheritance: PHP OOP


You need to a flashplayer enabled browser to view this YouTube video

YouTube Link: http://www.youtube.com/watch?v=vEubH2KVgYk [Watch the Video In Full Screen.]



Try yourselves:
If you try to extend class A and class B to class C, it’ll through fatal error.

Related Read:
Single Inheritance: PHP OOP

Note:
So, technically you can’t extend/inherit from more than 1 base/parent class.
To overcome this situation, we can make use of Interfaces.
Interfaces in PHP works similar to that of Java. We’ll teach interfaces in another video tutorial, so stay subscribed.

Preventing Inheritance and Overriding with final: PHP OOP

Video tutorial illustrating, how to prevent inheritance and overring using final keyword, in Object Oriented PHP.

stop-sign

In this program, we take two classes A and B, and then extend Class A to Class B.
Now using the final keyword, we’ll show how to avoid extending class A to class B or any other classes. Next, we’ll also show, how to use final keyword to prevent method overriding.

Avoiding Inheritance

1
2
3
4
5
6
7
8
9
10
11
< ?php
		final class A
		{
 
		}
 
		class B extends A
		{
 
		}
?>

This through’s following fatal error:

Fatal error: Class B may not inherit from final class (A) in C:\wamp\www\OOP\final.php on line 16

So, using the keyword final infront of the class name prevents it from inheritance.

Avoiding Overriding of method

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
< ?php
		class A
		{
			final function display()
			{
				echo "Inside class A";
			}	
		}
 
		class B extends A
		{
			function display()
			{
				echo "Inside class B";
			}
		}
?>

This through’s following fatal error:

Fatal error: Cannot override final method A::display() in C:\wamp\www\OOP\final.php on line 16

So, using the keyword final infront of the method name prevents it from being overriden.

Related:
If you want to know the basics of Inheritance and Overriding, go through this short notes before proceeding
Single Inheritance: PHP OOP
Overriding: PHP OOP

Preventing Inheritance and Overriding with final: PHP OOP


You need to a flashplayer enabled browser to view this YouTube video

YouTube Link: http://www.youtube.com/watch?v=NXsD908RSVE [Watch the Video In Full Screen.]



Sometimes preventing inheritance and avoiding overriding of certain methods becomes necessary inorder to maintain the sanity or data integrity while coding.

Overriding: PHP OOP

Video tutorial to illustrate Overriding in Object Oriented PHP Programming.

Here, we take two class: A and B. Extend class A to class B. Then, define method display() in class A.

Overriding is an object-oriented programming feature that enables a child class to provide different implementation for a method that is already defined and/or implemented in its parent class or one of its parent classes. The overriden method in the child class should have the same name, signature, and parameters as the one in its parent class.

Class B extends Class A

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
< ?php
		class A
		{
			function display()
			{
				echo "Inside Class A";
			}	
		}
 
		class B extends A
		{
 
		}
 
		$obj = new B();
		$obj->display();
?>

Next, redefine the same method display() inside class B too, with a different output.

Redefine method display inside class B

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
< ?php
		class A
		{
			function display()
			{
				echo "Inside Class A";
			}	
		}
 
		class B extends A
		{
			function display()
			{
				echo "Inside Class B";
			}	
		}
 
		$obj = new B();
		$obj->display();
?>

Now, the method inside class B has higher precedence over it’s parent class method.

Invoking parent method using Scope Resolution Operator

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
< ?php
		class A
		{
			function display()
			{
				echo "Inside Class A";
			}	
		}
 
		class B extends A
		{
			function display()
			{
    			  parent::display();
			}			
		}
 
		$obj = new B();
		$obj->display();
?>

You can invoke parent method from subclass by using the keyword parent followed by scope resolution operator and the method name.

Overriding: PHP OOP


You need to a flashplayer enabled browser to view this YouTube video

YouTube Link: http://www.youtube.com/watch?v=5tcIUn6nbVE [Watch the Video In Full Screen.]



Note:
1. Altering of function definition in the derived class does not alter the function definition in the parent class.
2. You can override both attributes and methods in the subclass.

Single Inheritance: PHP OOP

Inheritance is a way to reuse the code of existing objects.
In this video tutorial we’re illustrating single inheritance mechanism.

php-oop-single-inheritance

In this tutorial, we take a class called Vehicle with 3 attributes – color, accelerate and decelerate. And 3 methods – design, acceleration, deceleration.

Vehicle Class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
< ?php
		class Vehicle
		{
			public $color;
			public $accelerate;
			public $decelerate;
 
			function design($assign)
			{
				$this->color = $assign;
			}
			function acceleration($positive)
			{
				$this->accelerate = $positive;
			}
			function deceleration($negetive)
			{
				$this->decelerate = $negetive;
			}
		}
?>

Using the methods – design, acceleration and deceleration we assign values to the public attributes color, accelerate and decelerate.

Inherit Vehicle Class To Class Car
inheritance.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
< ?php
		class Vehicle
		{
			public $color;
			public $accelerate;
			public $decelerate;
 
			function design($assign)
			{
				$this->color = $assign;
			}
			function acceleration($positive)
			{
				$this->accelerate = $positive;
			}
			function deceleration($negetive)
			{
				$this->decelerate = $negetive;
			}
		}
 
		class Car extends Vehicle
		{
 
		}	
?>

Now create objects benze and bmw of class Car.

Objects of Class Car
vehicles.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
< ?php
		include_once("inheritance.php");
 
		$benze = new Car();
		$benze->design("Red");
		echo $benze->color;
 
		$bmw  = new Car();
		$bmw->design("Silver");
		echo "<br />".$bmw->color;
 
		$benze->acceleration(20);
		echo "<br />".$benze->accelerate;
 
		$benze->deceleration(5);
		echo "<br />".$benze->decelerate;	
?>

Here, using the methods – design, acceleration and deceleration we assign attribute values to individual cars.

Single Inheritance: PHP OOP


You need to a flashplayer enabled browser to view this YouTube video

YouTube Link: http://www.youtube.com/watch?v=pdDqtHlkzEY [Watch the Video In Full Screen.]



Uses of Inheritance:
Re-use of code.
Less and cleaner looking code.
Ease of understanding of code.
Ease of maintenance of project.

Access Specifiers: PHP OOP

Controlling Access with public, private and protected access modifiers.
These access specifiers can be used on both variables/attributes and methods.

In this video tutorial, we’ll demonstrate it using attributes.

Access Specifiers:
1. public
2. private
3. protected

Class With Attributes

1
2
3
4
5
6
7
8
9
< ?php
 class container
	 {
	 	var $a       = 10;
		public $b    = 20;
		private $c   = 30;
		protected $d = 40;
	 }
?>

var $a is similar to writing public $a

We shall extend class container to another class called contains.
Extending class is an inheritance property, and we shall discuss inheritance in another article. For now, know that, with extends keyword, all the properties and methods with public / protected access are inherited.

Extends

1
2
3
4
5
6
7
8
9
10
11
12
13
< ?php
	 class container
	 {
	 	var $a       = 10;
		public $b    = 20;
		private $c   = 30;
		protected $d = 40;
	 }
 
	 class contains extends container
	 {
	 }
?>

Here, contents of class container is extended by class contains.

Object of class container

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
< ?php
	 class container
	 {
	 	var $a       = 10;
		public $b    = 20;
		private $c   = 30;
		protected $d = 40;
	 }
 
	 class contains extends container
	 {
	 }
 
	 $obj1 = new container();
         echo $obj1->a;
         echo $obj1->b;
?>

This outputs: 10 and 20 respectively.

Object of class contains

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
< ?php
	 class container
	 {
	 	var $a       = 10;
		public $b    = 20;
		private $c   = 30;
		protected $d = 40;
	 }
 
	 class contains extends container
	 {
	 }
 
	 $obj2 = new contains();
         echo $obj2->a;
         echo $obj2->b;
?>

This outputs: 10 and 20 respectively.
i.e., public attributes are inherited

Accessing private / protected attributes outside class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
< ?php
	 class container
	 {
	 	var $a       = 10;
		public $b    = 20;
		private $c   = 30;
		protected $d = 40;
	 }
 
	 class contains extends container
	 {
	 }
 
	 $obj1 = new container();
         echo $obj1->c;
         echo $obj1->d;
?>

It through’s error, since you cannot access, private and protected variables/attributes outside the class.

Now lets check if private and protected variables are actually inherited:

Inheriting private attribute

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
< ?php
	 class container
	 {
	 	var $a       = 10;
		public $b    = 20;
		private $c   = 30;
		protected $d = 40;
	 }
 
	 class contains extends container
	 {
	 	function __construct()
		{
			echo $this->c;
		}
	 }
 
	 $obj1 = new contains();
?>

This through’s error, because $c is not inherited to class contains and thus not present inside class contains. Which means, private variables and methods cannot be inherited.

Inheriting protected attribute

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
< ?php
	 class container
	 {
	 	var $a       = 10;
		public $b    = 20;
		private $c   = 30;
		protected $d = 40;
	 }
 
	 class contains extends container
	 {
	 	function __construct()
		{
			echo $this->d;
		}
	 }
 
	 $obj1 = new contains();
?>

Output’s 40.
This means, protected variables and methods are inherited.

Access Specifiers: PHP OOP


You need to a flashplayer enabled browser to view this YouTube video

YouTube Link: http://www.youtube.com/watch?v=2Ow_cgBEGmk [Watch the Video In Full Screen.]



Conclusion
public attributes and methods are inherited and can be accessed outside the class.
private attributes and methods cannot be inherited and cannot be accessed outside the class.
protected attributes and methods can be inherited but cannot be accessed outside the class.

Constructors and Destructors: PHP OOP

Video tutorial illustrates the use of Constructor and Destructor functions in Object Oriented PHP Programming.

Constructor: A constructor is an initialization routine having the same name as the class name, which is called automatically at the time of object creation.

Earlier to PHP5, constructor function had the same name as the class name. From PHP version 5, constructor functions has this special name __construct
For version compatibility, if we do not have a __construct method, it falls back and looks for the method with the same name as the class name.

Destructor: Destructor method is automatically called when all the references to a class have been unset or fallen out of scope.

Default Constructor:

1
2
3
4
5
6
7
8
9
10
       class Info
	{
		private $name;
 
		function __construct()
		{
			$this->name = "Microsoft";
			echo $this->name;
		}
	}

A class called Info, which has one private variable called $name;
a default constructor which assigns the value Microsoft to the variable $name and then echos it out.

Parameterized Constructor:

1
2
3
4
5
6
7
8
9
10
11
        class Info
	{
		private $name;
 
		function __construct($text)
		{
			$this->name = $text;
			echo $this->name;
		}
      }
$a = new Info("Parameterized Constructor!");

Here we’re passing the parameter “Parameterized Constructor!”, which is then sent to __construct function which is intern assigned to the private variable $name and then echoed out.

Destructor:

1
2
3
4
5
6
7
8
9
10
11
class Info
	{
		private $name;
 
		function __destruct()
		{
 
			echo "<br />Destructor called!"
	       }
 
	}

Note: Destructor method do not take parameter/arguments.

Full Code of Class File
info.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
< ?php
    class Info
	{
		private $name;
 
		function __construct($text)
		{
			$this->name = $text;
			echo $this->name;
		}
 
		function __destruct()
		{
			echo "<br />Destructor called!"
		}
	}
?>

Here we have Info class, with 1 private variable and a construct(parameterized) method and a destructor method.

Application File or the Code Processing
index.php

1
2
3
4
5
< ?php
		include_once('info.php');
 
		$a = new Info("Parameterized Constructor!");
?>

We include the class file(info.php) and then instantiate Info class.
Once it’s instantiated, __construct function is called and all the code inside it will be executed.
At the end of the scope of this class, __destruct method is called and all the code inside destruct method is executed.

Constructors and Destructors: PHP OOP


You need to a flashplayer enabled browser to view this YouTube video

YouTube Link: http://www.youtube.com/watch?v=xsOO06A8gxU [Watch the Video In Full Screen.]



Usually programmers connect to the database in the __construct method and then close the database connection inside __destruct method.
But you could configure your database info inside config.php file and then auto-load your database.

I would usually, initialize API’s inside my __construct method. Use the API output inside my other member methods and then release the resources inside __destruct method.