0% found this document useful (0 votes)
5 views72 pages

PHHP & MYsql Unit 4

The document provides an overview of object-oriented programming (OOP) concepts in PHP, focusing on the creation and use of classes, objects, properties, and methods. It explains how to define a class, instantiate objects, and access or modify their properties, as well as introducing function overloading and its implementation using magic methods. The tutorial emphasizes the advantages of OOP, such as better code organization and modularity, while also providing practical examples of class usage.

Uploaded by

Bhuvan P.r
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views72 pages

PHHP & MYsql Unit 4

The document provides an overview of object-oriented programming (OOP) concepts in PHP, focusing on the creation and use of classes, objects, properties, and methods. It explains how to define a class, instantiate objects, and access or modify their properties, as well as introducing function overloading and its implementation using magic methods. The tutorial emphasizes the advantages of OOP, such as better code organization and modularity, while also providing practical examples of class usage.

Uploaded by

Bhuvan P.r
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 72

1.

Class Definition
class Car {

This defines a class called Car. A class is like a blueprint or template for creating objects.
The Car class will have properties (attributes) and methods (functions) associated with it.

2. Public Property
public $color;

Here, the class Car has a public property $color. In PHP, the public keyword means that
this property can be accessed directly from outside the class. This property is used to store the
color of the car.

3. Constructor Method
public function __construct($color) {
$this->color = $color;
}

This is a special method in PHP called a constructor (__construct). The constructor is


automatically called when an object of the class is created. The purpose of this constructor is
to initialize the object.

 public function __construct($color): This declares the constructor method


which takes one argument, $color.
 $this->color = $color;: Inside the constructor, we assign the passed $color
value to the $color property of the object. $this refers to the current object instance.

So, when a Car object is created, the constructor sets the initial value for the $color
property.

4. Method to Get the Color


public function getColor() {
return $this->color;
}

This is a public method named getColor. Its purpose is to return the value of the $color
property. Since $color is a property of the class, it can only be accessed through a method
like this (if encapsulation principles are followed).

 return $this->color;: This returns the value of the $color property of the current
object.
Classes, objects, methods and
properties
Object-oriented programming is a programming style in which it is
customary to group all of the variables and functions of a particular
topic into a single class. Object-oriented programming is considered to
be more advanced and efficient than the procedural style of
programming. This efficiency stems from the fact that it supports
better code organization, provides modularity, and reduces the need to
repeat ourselves. That being said, we may still prefer the procedural
style in small and simple projects. However, as our projects grow in
complexity, we are better off using the object oriented style.

With this tutorial, we are going to take our first steps


into the world of object oriented programming by
learning the most basic terms in the field:

classes

 objects

 methods

 properties

You'll learn
 How to create classes?
 How to add properties to a class?
 How to create objects from a class?
 How to get and set the objects' properties?
 How to add methods to a class?

How to create classes?


In order to create a class, we group the code that handles a certain
topic into one place. For example, we can group all of the code that
handles the users of a blog into one class, all of the code that is
involved with the publication of the posts in the blog into a second
class, and all the code that is devoted to comments into a third class.
To name the class, it is customary to use a singular noun that starts
with a capital letter. For example, we can group a code that handles
users into a User class, the code that handles posts into a Post class,
and the code that is devoted to comments into a Comment class.
For the example given below, we are going to create a Car class into
which we will group all of the code which has something to do with
cars.
1 2 3class Car {
// The code
}
 We declare the class with the class keyword.
 We write the name of the class and capitalize the first letter.

 If the class name contains more than one word, we capitalize each word. This is
known as upper camel case. For
example, JapaneseCars, AmericanIdol, EuropeTour, etc.
 We circle the class body within curly braces. Inside the curly braces, we put our
code.

How to add properties to a class?


We call properties to the variables inside a class. Properties can
accept values like strings, integers, and booleans (true/false values),
like any other variable. Let's add some properties to the Car class.
1 2 3 4 5class Car {
public $comp;
public $color = 'beige';
public $hasSunRoof = true;
}
 We put the public keyword in front of a class property.
 The naming convention is to start the property name with a lower case letter.

 If the name contains more than one word, all of the words, except for the first
word, start with an upper case letter. For example, $color or $hasSunRoof.
 A property can have a default value. For example, $color = 'beige'.
 We can also create a property without a default value. See the
property $comp in the above example.

How to create objects from a class?


We can create several objects from the same class,
with each object having its own set of properties.
In order to work with a class, we need to create an object from it. In
order to create an object, we use the new keyword. For example:
1$bmw = new Car ();
 We created the object $bmw from the class Car with the new keyword.
 The process of creating an object is also known as instantiation.

We can create more than one object from the same class.

1 2$bmw = new Car ();


$mercedes = new Car ();

In fact, we can create as many objects as we like from the same class,
and then give each object its own set of properties.

Objects, what are they good for?


While in the procedural style of programming, all of the functions and
variables sit together in the global scope in a way that allows their
use just by calling their name, the use of classes makes anything inside
the classes hidden from the global scope. That's because the code
inside the classes is encapsulated within the class scope, outside the
reach of the global scope. So, we need a way to allow the code from
the global scope to use the code within the class, and we do this by
creating objects from a class.

I say objects, and not object, because we can create as many objects
as we would like from the same class and they all will share the class's
methods and properties. See the image below:
From the same Car class, we created three individual objects with the
name of: Mercedes, Bmw, and Audi.

Although all of the objects were created from the same class and thus
have the class's methods and properties, they are still different. This is
not only, because they have different names, but also because they
may have different values assigned to their properties. For example, in
the image above, they differ by the color property - the Mercedes is
green while the Bmw is blue and the Audi is orange.

THE MESSAGE TO TAKE HOME IS:

A class holds the methods and properties that are shared by all of the
objects that are created from it.

Although the objects share the same code, they can behave differently
because they can have different values assigned to them.

How to get an object's properties?


Once we create an object, we can get its properties. For example:

1 2echo $bmw -> color;


echo $mercedes -> color;
 In order to get a property, we write the object name, and then dash greater than
(->), and then the property name.

 Note that the property name does not start with the $ sign; only the object name
starts with a $.
Result:beige
beige

How to set the object's properties?


In order to set an object property, we use a similar approach.

For example, in order to set the color to 'blue' in the bmw object:

1$bmw -> color = 'blue';


and in order to set the value of the $comp property for both objects:
1 2$bmw -> comp = "BMW";
$mercedes -> comp = "Mercedes Benz";

Once we set the value of a property, we can get its value.


In order to get the color of the $bmw object, we use the following line
of code:
1echo $bmw -> color;
Result:blue

We can also get the company name and the color of the second car
object.

1 2echo $mercedes -> color;


echo $mercedes -> comp;
Result:beige
Mercedes Benz

How to add methods to a class?


The classes most often contain functions. A function inside a class is
called a method. Here we add the method hello() to the class with the
prefix public.
1 2 3 4 5 6 7 8 91011class Car {

public $comp;
public $color = 'beige';
public $hasSunRoof = true;

public function hello()


{
return "beep";
}
}
 We put the public keyword in front of a method.
 The naming convention is to start the function name with a lower case letter.

 If the name contains more than one word, all of the words, except for the first
word, start with an upper case letter. For example, helloUser() or flyPanAm().

We can approach the methods similar to the way that we approach the
properties, but we first need to create at least one object from the
class.

1 2 3 4 5$bmw = new Car ();


$mercedes = new Car ();

echo $bmw -> hello();


echo $mercedes -> hello();
Result:beep
beep

Here is the full code that we have written during this tutorial:

12345678
9101112131415161718192021222324252627282930313233343536373839404
142434445<?php
// Declare the class
class Car {

// properties
public $comp;
public $color = 'beige';
public $hasSunRoof = true;

// method that says hello


public function hello()
{
return "beep";
}
}

// Create an instance
$bmw = new Car ();
$mercedes = new Car ();

// Get the values


echo $bmw -> color; // beige
echo "<br />";
echo $mercedes -> color; // beige
echo "<hr />";

// Set the values


$bmw -> color = 'blue';
$bmw -> comp = "BMW";
$mercedes -> comp = "Mercedes Benz";

// Get the values again


echo $bmw -> color; // blue
echo "<br />";
echo $mercedes -> color; // beige
echo "<br />";
echo $bmw -> comp; // BMW
echo "<br />";
echo $mercedes -> comp; // Mercedes Benz
echo "<hr />";

// Use the methods to get a beep


echo $bmw -> hello(); // beep
echo "<br />";
echo $mercedes -> hello(); // beep
Overloading in PHP
Last Updated : 15 Jun, 2022



What is function overloading? Function overloading is the ability to


create multiple functions of the same name with different
implementations. Function overloading in PHP? Function overloading in
PHP is used to dynamically create properties and methods. These dynamic
entities are processed by magic methods which can be used in a class for
various action types. Function overloading contains same function name
and that function performs different task according to number of arguments.
For example, find the area of certain shapes where radius are given then it
should return area of circle if height and width are given then it should give
area of rectangle and others. Like other OOP languages function
overloading can not be done by native approach. In PHP function
overloading is done with the help of magic function __call(). This function
takes function name and arguments.
Property and Rules of overloading in PHP:
 All overloading methods must be defined as Public.
 After creating the object for a class, we can access a set of entities that
are properties or methods not defined within the scope of the class.
 Such entities are said to be overloaded properties or methods, and the
process is called as overloading.
 For working with these overloaded properties or functions, PHP magic
methods are used.
 Most of the magic methods will be triggered in object context except
__callStatic() method which is used in a static context.
Types of Overloading in PHP: There are two types of overloading in PHP.
 Property Overloading
 Method Overloading
Property Overloading: PHP property overloading is used to create
dynamic properties in the object context. For creating these properties no
separate line of code is needed. A property associated with a class
instance, and if it is not declared within the scope of the class, it is
considered as overloaded property. Following operations are performed
with overloaded properties in PHP.
 Setting and getting overloaded properties.
 Evaluating overloaded properties setting.
 Undo such properties setting.
Before performing the operations, we should define appropriate magic
methods. which are,
 __set(): triggered while initializing overloaded properties.
 __get(): triggered while using overloaded properties with PHP print
statements.
 __isset(): This magic method is invoked when we check overloaded
properties with isset() function
 __unset(): Similarly, this function will be invoked on using PHP unset()
for overloaded properties.

<?php

//
class GFG {

// Location of overloading data


private $data = array();

// Overloading not used here


public $declared = 1;

// Overloading used when accessed


// outside the class
private $hidden = 2;

// Function definition
public function __set($name, $value) {
echo "Setting '$name' to '$value'\n";
$this->data[$name] = $value;
}

// Function definition
public function __get($name) {
echo "Getting '$name: ";
if (array_key_exists($name, $this->data)) {
return $this->data[$name];
}

$trace = debug_backtrace();

return null;
}

// Function definition
public function __isset($name) {
echo "Is '$name' set?\n";
return isset($this->data[$name]);
}

// Definition of __unset function


public function __unset($name) {
echo "Unsetting '$name'\n";
unset($this->data[$name]);
}

// getHidden function definition


public function getHidden() {
return $this->hidden;
}
}

// Create an object
$obj = new GFG;

// Set value 1 to the object variable


$obj->a = 1;
echo $obj->a . "\n";

// Use isset function to check


// 'a' is set or not
var_dump(isset($obj->a));

// Unset 'a'
unset($obj->a);

var_dump(isset($obj->a));

echo $obj->declared . "\n\n";


echo "Private property are visible inside the class ";
echo $obj->getHidden() . "\n\n";

echo "Private property are not visible outside of class\n";


echo $obj->hidden . "\n";

?>

Output:
Setting 'a' to '1'
Getting 'a: 1
Is 'a' set?
bool(true)
Unsetting 'a'
Is 'a' set?
bool(false)
1

Private property are visible inside the class 2

Private property are not visible outside of class


Getting 'hidden:
Method Overloading: It is a type of overloading for creating dynamic
methods that are not declared within the class scope. PHP method
overloading also triggers magic methods dedicated to the appropriate
purpose. Unlike property overloading, PHP method overloading allows
function call on both object and static context. The related magic functions
are,
 __call() – triggered while invoking overloaded methods in the object
context.
 __callStatic() – triggered while invoking overloaded methods in static
context.
<?php
class GFG {

public function __call($name, $arguments) {

echo "Calling object method '$name' "


. implode(', ', $arguments). "\n";
}

public static function __callStatic($name, $arguments) {

echo "Calling static method '$name' "


. implode(', ', $arguments). "\n";
}
}

// Create new object


$obj = new GFG;

$obj->runTest('in object context');

GFG::runTest('in static context');

?>

What is InheritanceInheritance is one of the four pillars


of Object-Oriented Programming (OOPs). Inheritance is
the phenomenon by which a child class can inherit all the
properties and characteristics of the parent class.

You can understand this with a simple real-life example. Consider the example
of human beings. You inherit characteristic features from the class ‘Humans’,
such as walking, sitting, running, eating, etc. The class ‘Humans’ inherits from
the class ‘Mammal’, these characteristic features - making the class ‘Human' a
derived class of ‘Mammal’. Furthermore, the class ‘Mammal’ gets its
characteristic features from another yet another class - ‘Animal’. This makes the
class ’Mammal’ a derived class of the ‘Animal’ class; also making the ‘Animal’
class a base class.

Inheritance in PHP

Inheritance in PHP is an important OOPs concept and can not be overlooked.


Understanding inheritance in PHP is necessary to get a holistic view of object-
oriented concepts in PHP.

Inheritance provides you with many benefits that make PHP programming a lot
more convenient. One such benefit is code reusability. Reusability allows you to
generate clean code and the replication of code gets reduced to almost zero.
Reusing existing codes serves various advantages. It saves time, cost, effort, and
increases a program’s reliability. Moreover, the program becomes intuitive.

PHP offers mainly three types of inheritance based on their functionality. These
three types are as follows:

 Single Inheritance: Single inheritance is the most basic or fundamental type


of inheritance offered by PHP. There is only one base class and one
sub/derived class in a single inheritance and the subclass is directly inherited
from the base class.
 Hierarchical Inheritance: As the name suggests, the hierarchical inheritance
adopts a tree-like structure, where multiple derived classes are inherited from
the base class.
 Multilevel Inheritance: Multilevel inheritance is the third type of inheritance
supported in PHP. It occurs at different levels. Here, one base class is
inherited by a derived class, then that derived class is inherited by other
derived classes, and so on.

The Syntax for Inheriting a Class in PHP

Depicted below is the syntax that is used to extend a base class in PHP.
class derived_class_name extends base_class_name {

// define member functions of

// the derived class here.

The keyword extends is used to define a derived or child class in PHP.

 derived_class_name: It specifies the name of the derived or the child class.


The child class, also known as a subclass, inherits its salient features or
characteristics from its parent class. There can be one or over one derived
class that inherits from the same base class depending on what type of
inheritance is performed. There are three visibility modes supported in PHP:
Public, Private, and Protected, which specify how the derived class will
inherit what.

 base_class_name: It specifies the name of the base or the parent class from
which the child class is inheriting its properties. A base class is also known as
a parent class because all the classes that are termed as derived classes or
child classes inherit their properties from the base class. There can be one or
more base classes in a program, depending upon the type of inheritance. For
instance, in a single-level inheritance, there will be one base class for one
child class, but in a multilevel inheritance, one child class can inherit from
over one base class in more than one level.

Access Modifiers in PHP

The access modifier (private, public, or protected) used in the definition of the
member functions and data members of the derived class specifies the mode
with which the features of the base class are derived. The access modifier
controls where and how the data members and member functions of a base class
can be inherited by the child classes. These access modifiers are used to restrict
the access of the base class from the child class to encapsulate the data. This is
popularly known as data hiding.

In PHP, there are three access modifiers:


 Public:

Public access modifier gives the least privacy to the attributes of the base class.
If the access modifier is public, it means that the derived class can access the
public and protected members of the base class but not the private members of
the base class.

The following example shows a class with public members:

class derived_class_name extends base_class_name

// public data member

public $var_name;

// public member function

public function function_name()

// define the function here

The following program illustrates the public access modifier in PHP:

<?php

// Define the base class

class Jewellery {

public $price = "We have a fixed price of 100000";


function printMessage() {

echo $this->price;

echo PHP_EOL;

// define the derived classes

class Necklace extends Jewellery {

function print(){

echo $this->price;

echo PHP_EOL;

// create the object of the

// derived class.

$obj= new Necklace;

// call the functions

echo $obj->price;

echo PHP_EOL;

$obj->printMessage();

$obj->print();
?>

 Private:

Private access modifier provides the maximum privacy to the attributes of a


base class. You can access a privately declared data member or member
function only within the class in which they are declared.

The following example demonstrates a class with private members:

class derived_class_name extends base_class_name

// private data member

private $var_name;

// private member function

private function function_name()

// define the function here


}

Although the direct accessibility of a private member is not possible, you can
access them indirectly using public member functions in the class. If the private
members are accessed by a public member in a class, then any child class
accessing this public function can also access that private member.

The following program illustrates the private access modifier in PHP:

<?php

// Define the base class

class Jewellery {

private $price = "We have a fixed price of 100000";

private function show()

echo "This is a private method of a base class";

// define the derived classes

class Necklace extends Jewellery {

function printPrice()

echo $this->price;
}

// create the object of the

// derived class

$obj= new Necklace;

// this line is trying to

// call a private method.

// this will throw error

$obj->show();

// this will also throw error

$obj->printPrice();

?>

In this program, you’re trying to access a private member directly in a derived


class. That’s why it’s throwing an error.

 Protected:
Protected access modifier provides an intermediate privacy level to the
members of a class. If the access specifier is protected, this means that the
derived class can access the public and protected members of the base class.
The protected members of a base class can be accessed within that class and by
its child classes.

The following example demonstrates a class with protected members:

class derived_class_name extends base_class_name

// protected data member

protected $var_name;

// protected member function

protected function function_name()

// define the function here

The following program illustrates the protected access modifier in PHP:

<?php

// Define the base class

class Jewellery {

protected $price1 = 10000;

protected $price2 = 20000;


// Subtraction Function

function total()

echo $sum = $this->price1 + $this->price2;

echo PHP_EOL;

// define the derived classes

class Necklace extends Jewellery {

function printInvoice()

$tax = 100;

echo $sub = $this->price1 + $this->price2 + $tax;

echo PHP_EOL;

$obj= new Necklace;

$obj->total();

$obj->printInvoice();
?>

Child Class With Its Own Methods and Properties

In inheritance, the purpose of inheriting the properties and members of a base


class by a child class is well achieved. When a child class inherits from a base
class, it has direct access to all the non-private members of the base class. And
even the private members can be accessed indirectly.

However, a child class can also have its own methods and properties. Apart
from the members of the base class, a derived class can have as many data
members and methods as you want. A derived class is just like any other class,
with the benefit of having access to some other methods and properties of a base
class. This is what inheritance is all about.

The following program illustrates a child class having access to the properties of
its base class along with its methods and properties:

<?php

// Define the base class

class base_class {
// data member of the base class

public $data_mem = 10;

// member function of the base class

public function member_func()

echo "I am the base class function.";

echo "I am the base class data member: ";

echo $this->data_mem;

// define the derived classes

class child_class extends base_class {

// member function of the child class

function child_func()

{ echo "I am the child class function.";

echo $this->data_mem;

// create the object of the

// derived class
$obj= new child_class;

// call method of the base class

$obj->member_func();

// call method of the child class

$obj->child_func();

?>

Types of Inheritance in PHP

The following three types of inheritance are supported in PHP.

 Single Inheritance

Single inheritance is the most basic and simple inheritance type. As the name
suggests, in a single inheritance, there is only one base class and one sub or
derived class. It directly inherits the subclass from the base class.
The following program illustrates single level inheritance in PHP:

<?php

// base class named "Jewellery"

class Jewellery {

var $cost = 10000;

public function printName($name) {

echo 'This is base class: Jewellery & name of jewellery is: ' . $name .
PHP_EOL;

// derived class named "Necklace"

class Necklace extends Jewellery {

public function printName($name) {

echo 'This is child class: Necklace & name of jewellery is: ' . $name .
PHP_EOL;

// this class can access


// data member of its parent class.

echo 'Price is: ' . $this->cost . PHP_EOL;

$f = new Jewellery();

$s = new Necklace();

$f->printName('Ring');

$s->printName('Necklace');

?>

 Multilevel Inheritance

Multilevel Inheritance is another type of inheritance that is found in PHP.


Multilevel inheritance can also be explained by a family tree. There is one base
class. This base class can be inherited by. These subclasses (not every subclass
necessarily) act as base class and are further inherited by other subclasses. This
is just like a family having descendants over generations.
The following program illustrates multilevel inheritance in PHP:

<?php

// base class named "Jewellery"

class Jewellery {

public function totalCost() {

return ' total jewellery cost: 600000';

// derived class named "Necklace"

// inherited form class "Jewellery"

class Necklace extends Jewellery {

public function necklace() {


return ' necklace cost: 450000';

// derived class named "Pendant"

// inherited form class "Necklace"

class Pendant extends Necklace {

public function pendantCost() {

return ' pendant cost: 600000';

public function priceList() {

echo '1. ' .$this->totalCost() . PHP_EOL;

echo '2. ' .$this->necklace() . PHP_EOL;

echo '3. ' .$this->pendantCost() . PHP_EOL;

// creating object of

// the derived class

$obj = new Pendant();

$obj->priceList();

?>
 Hierarchical Inheritance

As the name suggests, hierarchical inheritance shows a tree-like structure. Many


derived classes are directly inherited from a base class. In this type of
inheritance, more than one derived class shares the same parent class.

The following program illustrates hierarchical inheritance in PHP:

<?php
// base class named "Jewellery"

class Jewellery {

public function Jewellery() {

echo 'This class is Jewellery ' . PHP_EOL;

// derived class named "Necklace"

class Necklace extends Jewellery {

// derived class named "Necklace"

class Bracelet extends Jewellery {

// creating objects of

// derived classes

// "Necklace" and "Bracelet"

$n = new Necklace();

$b = new Bracelet();

?>
Protected Access Modifier in PHP

As discussed earlier, protected members of a class can only be accessed within


that class and by the derived classes that inherit it. Even an instance of the
derived class cannot access the protected member of its base class, outside of
that class. This means that the protected members can be accessed only by a
derived class and the base class itself, and not anywhere else in the program.

The following programs illustrate the accessibility of protected members in


PHP:

<?php

// base class named "Jewellery"

class Jewellery {

public $cost = 10000;

// protected member function

// of the base class

protected function display() {


echo 'This is the base class.' . PHP_EOL;

// derived class named "Necklace"

class Necklace extends Jewellery {

public function show() {

echo 'This is the child class. ' . PHP_EOL;

// create an object of the derived class

$obj = new Necklace();

// call function of derived class

$obj->show();

// call "protected" function of base class

$obj->display(); // this will throw error

?>
In the above program, an instance of the derived class tries to call a protected
member function of its base class outside both of the classes. That’s why the
program is throwing an error.

This issue can be solved using a public method. Since a protected member can
be directly accessed inside the derived class, so calling the protected member in
a public method of the derived class makes it possible to achieve the task of
accessing the protected member indirectly.

The following program illustrates this:

<?php

// base class named "Jewellery"

class Jewellery {

public $cost = 10000;

// protected member function

// of the base class

protected function display() {

echo 'This is the base class.' . PHP_EOL;

}
}

// derived class named "Necklace"

class Necklace extends Jewellery {

public function show() {

echo 'This is the child class. ' . PHP_EOL;

// protected member function of the base class

// can be accessed in this derived class

$this->display();

// create an object of the derived class

$obj = new Necklace();

// call function of derived class

$obj->show();

?>
Overriding Inherited Methods in PHP

Function overriding is supported by inheritance in PHP. It can be observed


when a derived class and base class both contain a function having the same
name. Both the functions should have the same number of arguments. The
derived class inherits the member functions and data members from its base
class. So to override a certain functionality, you perform function overriding.

The following program illustrates the concept of method overriding in PHP:

<?php

// base class named "base_class"

class base_class {

// "show" function of the base class

public function show() {

echo 'This is the base class.' . PHP_EOL;

}
}

// derived class named "derived_class"

class derived_class extends base_class {

// "show" function of the derived class

public function show() {

echo 'This is the derived class. ' . PHP_EOL;

// create an object of the derived class

$obj = new derived_class();

// will call the "show"

// function of the derived class

$obj->show();

?>
In the program above, both the base class (i.e. base_class) and the derived class
(i.e. derived_class) have a function called “show”. If an instance of the derived
class calls the show() function, then PHP will call the show() function of the
derived call. This is because the derived_class overrides the show() of the
base_class with its own show() method. If an instance of the base class uses the
show() method, then there will be no overriding of the method.

The Final Keyword in PHP

Final is a critical keyword in OOPs concepts in PHP and is found in various


programming languages such as Java, JavaScript, etc. However, the Final
keyword serves different purposes in different languages.

In PHP, the final keyword serves different purposes depending upon whether
it’s used with a class or a method.

 The final keyword used with a class: The final keyword with a class, serves
the purpose of preventing inheritance. If a class is declared final, using the
keyword “final”, then inheriting that class will cause the program to throw an
error. This can be useful in a case when you don’t want a class and its
members to be accessed anywhere else in the program.
The following program illustrates the concept of the “final” keyword with
classes in PHP:

Note: This code will throw an error as we are trying to inherit a final class.

<?php

final class Jewellery {

final function displayMessage() {

echo "I am a final class. You can not inherit my properties!";

function print() {
echo "I am the Jewellery class function.";

class testClass extends Jewellery {

function show() {

echo "I am the test class function.";

$obj = new testClass;

$obj->show();

?>

 The final keyword used with a method: The final keyword when used with a
method, serves the purpose of preventing method overriding. If a method has
been declared final, using the “final” keyword, then another function with the
same name and same parameters can not be defined in a derived class.
Calling such a function will cause the program to throw an error.
The following programs illustrate the concept of the “final” keyword with
methods in PHP:

Without the final keyword (will produce output, but will cause method
overriding)

<?php

class Jewellery {

function printMessage() {

echo "I am the function of derived class.";

class testClass extends Jewellery {

function printMessage() {

echo "I am the function of derived class.";

$ob = new testClass;

$ob->printMessage();

?>
With the final keyword. (WIll throw an error, to prevent method overriding).

<?php

class Jewellery {

final function printMessage() {

echo "I am the function of derived class.";

class testClass extends Jewellery {

function printMessage() {

echo "I am the function of derived class.";

}
$ob = new testClass;

$ob->printMessage();

?>

Multiple Inheritance in PHP Using Traits or Interfaces

Multiple inheritance is a type of inheritance in which one class can inherit the
properties from more than one parent class. In this type of inheritance, there is
one derived class, that is derived from multiple base classes. This is one of the
most important and useful concepts provided in the object-oriented paradigm
and serves the purpose wherein you want one class to inherit different types of
properties (which are in different classes).

For example, consider a class called parrot. Now, since a parrot is a bird, and it
can also be a pet or simply a living creature, so, the class parrot can serve
different properties. So, using multiple inheritance, the parrot class can inherit
the properties of all three classes bird, pet, and living_creature.
Many programming languages do not support multiple inheritance directly
like Java and PHP. However, PHP provides some ways to implement multiple
inheritance in your programs. In the PHP programming language, multiple
inheritance is achieved by using two ways:

 Traits:

Traits are used to reduce the complexity of a program by writing consistent


functionalities that can be used by other classes in the program. A trait is like a
class, it can have functions as well as abstract methods. The functionalities
defined in a trait can be accessed by other classes in the PHP program.

The traits can be used to implement the concept of multiple inheritance in PHP.

Syntax

class derived_class_name extends base_class_name {

use trait_name; // “use” keyword to use a trait

...

...

// base_class functions

}
The following program illustrates the usage of traits to implement multiple
inheritance:

<?php

// declare a class

class Bird {

public function display() {

echo "I am a bird,";

// declare a trait

trait Pet {

public function show() {

echo " a pet";

// declare a derived class

class Parrot extends Bird {

// keyword "use" to use the trait

use Pet;

public function msg() {


echo ", and a parrot.";

// declare object of the derived class

$test = new Parrot();

$test->display();

$test->show();

$test->msg();

?>

 Interfaces:

Interfaces are used when there are objects that share the same functionality, but
you don’t want the objects to know about each other. In other words, an
interface provides contracts for the objects, without knowing anything else
about one another.

Interfaces can also be used to implement multiple inheritance in PHP.


Syntax

// use the keyword "implement"

// to use interface

class derived_class extends base_class implements interface_name

The following program illustrates the usage of interfaces to implement multiple


inheritance:

<?php

// define a class

class Bird {

public function insideBird() {

echo "I am bird, ";

// declare an interface

interface Pet {

public function insidePet();

// define a derived class

// inherited from Bird class

// and implementing Pet interface


class Parrot extends Bird implements Pet {

function insidePet() {

echo "and a pet, ";

public function insideParrot() {

echo "and a parrot.";

// create object of the derived class

$obj = new Parrot();

$obj->insideBird();

$obj->insidePet();

$obj->insideParrot();

?>
Importance of Inheritance in PHP

Inheritance in itself is one of the most important concepts introduced in object-


oriented programming. Following are some of the key points highlighting the
importance of inheritance in PHP:

 Code reusability: Inheritance strongly supports code reusability. Since the


functionalities and properties of one class can be inherited and used by other
classes, there is no need to write those functionalities repeatedly in different
sections of the program.
 Data hiding: Data hiding is one of the most important aspects of inheritance.
Accessibility of the data can be easily controlled by using the access
modifiers, and only the required data is allowed to access outside the class.
 Extensibility: Inheritance provides a way to write extensible programs. This
means that the required functionalities or classes can be extended when there
is a requirement in the future growth of the program or application.
 Overriding: The concept of method overriding can be easily achieved in PHP.
The methods of a base class can be redefined in the derived class as per the
requirement of the program. Those functions are overridden in the derived
class, without causing any errors.
 Reduced complexity: The complexity of code is also reduced as common
properties can be simply inherited, without the need to redeclare them. This
makes the code convenient.

PHP | Constructors and Destructors




In PHP, constructors and destructors are special methods that are used in
object-oriented programming (OOP). They help initialize objects when they
are created and clean up resources when the object is no longer needed.
These methods are part of the class lifecycle.
In this article, we will discuss what constructors and destructors are and
how to use them.
What are Constructors in PHP?
A constructor is a special function or method in a class that is automatically
called when an object of the class is created. The constructor is mainly
used for initializing the object, i.e., setting the initial state of the object by
assigning values to properties.
Syntax:
<?php
class ClassName {
public function __construct() {
// Constructor code here
}
}
?>
Now, let us understand with the help of the example:

<?php
class Car {
public $model;
public $color;
// Constructor
public function __construct($model, $color) {
$this->model = $model;
$this->color = $color;
}

public function display() {


echo "Model: $this->model, Color: $this->color";
}
}
$myCar = new Car("Tesla", "Red");
$myCar->display();
?>

Output
Model: Tesla, Color: Red
In this example:
 The constructor __construct() is used to initialize the properties $model
and $color when an object of the Car class is created.
 When the object $myCar is created, the constructor is called
automatically with "Tesla" and "Red" passed as arguments, thus
initializing the car's properties.
 The display() method is used to print the car details.
What are Destructors in PHP?
A destructor is a special method in PHP that is automatically called when
an object is destroyed or goes out of scope. It is mainly used for cleaning
up or releasing resources that the object might have acquired during its
lifetime, such as closing file handles or database connections.
Syntax:
<?php
class ClassName {
public function __destruct() {
// Destructor code here
}
}
?>

<?php
class Database {
public $connection;
// Constructor to initialize the connection
public function __construct($hostname) {
$this->connection = "Connected to database at $hostname";
echo $this->connection;
}

// Destructor to close the connection


public function __destruct() {
echo "\nConnection closed.";
}
}

$db = new Database("localhost");


?>
Output
Connected to database at localhost
Connection closed.
In this example:
 The constructor establishes a database connection (a simulated
message in this case).
 The destructor is automatically called when the object goes out of scope
or when the script finishes executing.
 It cleans up by outputting a message indicating that the connection is
 Closed.

When are Constructors and Destructors Called?


 Constructors: A constructor is called when you create an object of a
class using the new keyword. It is executed automatically during object
creation.
$obj = new ClassName(); // Calls __construct()
 Destructors: A destructor is called when an object is destroyed. It is
called automatically when the object is no longer in use.
unset($obj); // Calls __destruct() manually
Constructor and Destructor with Inheritance
When a class extends another class, the constructor of the parent class is
not automatically called. However, the destructor of the parent class is
automatically called when the child class is destroyed.

<?php

class Animal {

public $name;

// Constructor in Parent Class

public function __construct($name) {

$this->name = $name;

echo "$this->name is an animal. \n";

// Destructor in Parent Class

public function __destruct() {

echo "Animal $this->name is destroyed. \n";

class Dog extends Animal {

// Constructor in Child Class

public function __construct($name) {

parent::__construct($name); // Calling Parent Constructor

echo "$this->name is a dog. \n";


}

// Destructor in Child Class

public function __destruct() {

echo "$this->name is no longer a dog. \n";

parent::__destruct(); // Calling Parent Destructor

$dog = new Dog("Rex");

unset($dog);
?>

Output
Rex is an animal.
Rex is a dog.
Rex is no longer a dog.
Animal Rex is destroyed.
In this example:
 The parent class, Animal, has its constructor to set the name and
display a message.
 The child class Dog calls the parent constructor using
parent::__construct($name).
 Both the constructor and destructor of the parent and child classes are
executed.
Best Practices for Constructors and Destructors
Constructors
 Always initialize the properties of the object inside the constructor.
 If you need to pass arguments to the constructor, make sure to
document them.
 Constructors should not contain logic that affects program flow (e.g.,
database queries, heavy processing).
Destructors
 Use destructors to release any resources that your object may have
acquired, such as database connections, file handlers, or network
connections.
 Avoid using complex logic in destructors, as they are mainly intended for
cleanup.
 Destructors should not raise exceptions or output data (unless
necessary).
Constructors vs Destructors
Constructors Destructors

Accepts one or more arguments. No arguments are passed. It's void.

Has the same name as the class, with a tilde


Has the same name as the class.
(~) prefix.

Used to initialize the instance of a Used to de-initialize objects to free up


class. memory.

Constructors can be overloaded. Destructors cannot be overloaded.

It is called at the time the object is It is called automatically at the time of object
created. deletion.

Allocates memory. It deallocates memory.

Multiple constructors can exist in a


Only one Destructor can exist in a class.
class.

Conclusion
Constructors and Destructor methods are very useful as they make very c
tasks easier during coding. These encourage re-usability of code without
unnecessary repetition. Both of them are implicitly called by the compiler,
even though they are not defined in the class.
PHP Form Handling
Last Updated : 14 Apr, 2025



Form handling is the process of collecting and processing information that


users submit through HTML forms. In PHP, we use special tools called
$_POST and $_GET to gather the data from the form. Which tool to use
depends on how the form sends the data—either through the POST
method (more secure, hidden in the background) or the GET method (data
is visible in the URL).
 Collecting Data: Retrieving form data using PHP.
 Validating Data: Ensuring that the input meets expected formats.
 Sanitizing Data: Cleaning up the data to prevent malicious content.
 Processing Data: Using the data for its intended purpose (e.g., saving
to a database, sending an email, etc.).
 Returning a Response: Displaying feedback to the user or redirecting
them to another page.
Form Attributes
 action: The action attribute specifies the URL where the form data will
be sent when the form is submitted.
<form method="post" action="process_form.php">
 method: The method attribute specifies the HTTP method (GET or
POST) to use when sending form data.
<form method="post" action="process_form.php">
 name: The name attribute is crucial in PHP form handling, as it is used
to refer to the data submitted by the form fields.
$username = $_POST['username']; // Accessing the form data
 target: The target attribute specifies where to display the response after
submitting the form. It determines where the resulting page (or
response) will appear once the form is submitted.
<form method="post" action="process_form.php" target="_blank">
<input type="text" name="username" required>
<input type="submit" value="Submit">
</form>
 enctype: The enctype (encoding type) attribute defines how the form
data should be encoded when submitted to the server. This is
particularly important when submitting forms that include file uploads.
Form Elements
Form processing contains a set of controls through which the client and
server can communicate and share information. The controls used in forms
are:
 Input Field: Input field is the most common form element, allowing
users to input a single line of text, such as their name, address, or any
other simple text information.
<input type="text" name="fullname" required>
 Password Input Field: The password input field hides the text entered,
making it suitable for secure data entry like passwords.
<input type="password" name="password" required>
 Checkboxes: Checkboxes allow users to select multiple options from a
set of choices. They are often used for lists of features or permissions.
<input type="checkbox" name="subscribe" value="yes"> Subscribe
to newsletter
 Radio Buttons: Radio buttons allow the user to choose only one option
from a set of predefined options. This is useful for binary choices, such
as gender selection.
<input type="radio" name="gender" value="female"> Female
<input type="radio" name="gender" value="male"> Male
 Textarea: The textarea element allows users to input multiple lines of
text, making it useful for longer messages, feedback, or comments.
<textarea name="message" rows="5" cols="40"
required></textarea>
Creating a Simple Form

<html>

<body>

<form method="post" action="<?php echo


htmlspecialchars($_SERVER["PHP_SELF"]); ?>">

<table>

<tr>

<td>Full Name:</td>

<td><input type="text" name="fullname"></td>

</tr>

<tr>
<td>Email Address:</td>

<td><input type="email" name="user_email"></td>

</tr>

<tr>

<td>Age:</td>

<td><input type="text" name="user_age"></td>

</tr>

<tr>

<td>Feedback:</td>

<td><textarea name="user_feedback" rows="4"


cols="40"></textarea></td>

</tr>

<tr>

<td>Gender:</td>

<td>

<input type="radio" name="user_gender"


value="female">Female

<input type="radio" name="user_gender" value="male">Male

</td>

</tr>

<tr>

<td colspan="2"><input type="submit" name="submit"


value="Submit"></td>

</tr>

</table>
</form>

<?php

$fullname = $user_email = $user_gender = $user_feedback =


$user_age = "";

// Check if the form was submitted

if ($_SERVER["REQUEST_METHOD"] == "POST") {

// Only process the POST data if the form is submitted

if (isset($_POST['fullname'])) {

$fullname = htmlspecialchars($_POST['fullname']);

if (isset($_POST['user_email'])) {

$user_email = htmlspecialchars($_POST['user_email']);

if (isset($_POST['user_age'])) { // Corrected variable to user_age

$user_age = htmlspecialchars($_POST['user_age']);

if (isset($_POST['user_feedback'])) {

$user_feedback = htmlspecialchars($_POST['user_feedback']);

if (isset($_POST['user_gender'])) {

$user_gender = htmlspecialchars($_POST['user_gender']);

}
}

// Display the submitted details

echo "<h2>Details Submitted:</h2>";

echo "Full Name: " . $fullname . "<br>";

echo "Email: " . $user_email . "<br>";

echo "Age: " . $user_age . "<br>";

echo "Feedback: " . $user_feedback . "<br>";

echo "Gender: " . $user_gender;

?>

</body>
</html>

What is MySQL?
Last Updated : 28 Apr, 2025



MySQL is an open-source, relational database management system


(RDBMS) that uses Structured Query Language (SQL) to manage and
manipulate data. It is one of the most popular database systems used in
web applications, known for its speed, reliability, and ease of use. MySQL
is commonly used in conjunction with programming languages such as
PHP, Java, and Python to build dynamic websites and applications.
 It is developed by Oracle Corporation.
 It supports multiple platforms like Windows, Linux, and macOS.
 It is widely used by developers for its scalability, data security features,
and extensive community support.
 MySQL powers a large number of websites from small personal blogs to
large-scale enterprise applications, making it a fundamental technology
for modern data-driven development.

What is MySQL?
In this article, we will explore the importance of MySQL with its uses and
discover why it is so important in databases.
Key Features in MySQL
MySQL is a popular choice for managing relational databases for several
reasons:
 Open-Source: MySQL is free and open-source, allowing modification
and distribution.
 High Performance: It offers fast data retrieval and processing for large
datasets.
 ACID Compliance: Ensures data integrity and reliability, especially with
InnoDB storage.
 Scalability: Supports large databases and high traffic with features like
partitioning and clustering.
 Multiple Storage Engines: Offers different storage engines (e.g.,
InnoDB, MyISAM) for flexible use.
 Replication: Supports master-slave replication for data redundancy and
high availability.
 Security Features: Provides user authentication, SSL encryption, and
secure data storage options.
Who Uses MySQL
MySQL is a widely-used relational database management system
(RDBMS) that caters to various user groups, from small businesses to
large enterprises. Here's a look at who uses MySQL:
 Small to Medium-Sized Businesses (SMBs): MySQL is popular
among SMBs due to its cost-effectiveness, ease of use, and flexibility.
These businesses leverage MySQL for managing their customer data,
sales transactions, and other operational databases.
 Large Enterprises: Many large organizations use MySQL for its
scalability and reliability. Companies like Facebook, Google, and Adobe
rely on MySQL to handle large-scale databases and high-traffic
applications.
 Web Developers: MySQL is a favorite among web developers because
it integrates seamlessly with popular web development technologies
such as PHP and JavaScript. It powers many websites and web
applications, from blogs to e-commerce platforms.
 Educational Institutions: MySQL is frequently used in academic
settings for teaching database management and SQL skills. Its open-
source nature makes it a cost-effective choice for educational purposes.
Applications of MySQL
MySQL has used in various applications across a wide range of industries
and domains, because of to its versatility, reliability, and performance. Here
are some common applications :
 E-commerce: MySQL is extensively used in e-commerce platforms for
managing product catalogs, customer data, orders, and transactions.
 Content Management Systems (CMS): Many popular CMS platforms
rely on MySQL as their backend database to store website
content, user profiles, comments, and configuration settings.
 Financial Services: MySQL is employed in financial applications,
including banking systems, payment processing platforms, and
accounting software, to manage transactional data, customer
accounts, and financial records.
 Healthcare: MySQL is used in healthcare applications for storing and
managing patient records, medical histories, treatment plans, and
diagnostic information.
 Social Media: MySQL powers the backend databases of many social
media platforms, including user profiles, posts, comments, likes, and
connections.
The Cloud and the Future of MySQL
The cloud has significantly influenced the evolution of MySQL, shaping its
future in several ways:
Cloud Integration:
 Managed Services: Cloud providers such as Amazon Web Services
(AWS), Google Cloud Platform (GCP), and Microsoft Azure offer
managed MySQL services (e.g., Amazon RDS, Google Cloud SQL) that
simplify database management, scaling, and maintenance.
 Scalability: Cloud environments enable dynamic scaling of MySQL
databases, allowing users to adjust resources based on demand without
significant upfront investments.
Enhanced Features:
 High Availability: Cloud-based MySQL solutions often come with built-
in high availability and disaster recovery options, improving resilience
and uptime.
 Automatic Backups: Cloud services provide automated backup
solutions, ensuring data integrity and ease of recovery.
Future Trends:
 Hybrid Cloud Deployments: Organizations are increasingly adopting
hybrid cloud strategies, integrating MySQL databases across on-
premises and cloud environments for greater flexibility and performance.
 Advanced Analytics: The integration of MySQL with cloud-based
analytics and machine learning platforms is likely to grow, enabling more
advanced data analysis and insights.
 Serverless Architectures: As serverless computing continues to
evolve, MySQL may adapt to serverless environments, offering more
efficient and cost-effective solutions for database management.
Difference Between MySQL and SQL
MySQL SQL

SQL (Structured Query Language) is a


MySQL is a Relational Database
standard language used for
Management System (RDBMS) that
communicating with relational
uses SQL (Structured Query Language).
databases.

It is open source and accessible to any and


It is not an open-source language.
everyone for free.
MySQL SQL

It supports basic programming languages It is in itself a Query language used for


like C, C++, Python, Ruby, etc. database systems.

It available only in the English language. It is available in different languages.

It doesn't support user-defined functions It supports user-defined functions and


and XML. XML.

MySQL Data Types

Overview
MySQL offers various unique features to its users and one such feature is its ability
to handle various types of data. Data types are a building block of any
programming language. In MySQL, data types determine the type of value you can
store in a column of a table so it is very important to understand the basics of the
vast variety of data types that MySQL offers.

In MySQL, there are several data types, including string, numeric, date and time,
spatial, and JSON. In this article, we will provide an overview of each of these data
types, including their description, default values, storage requirements, and how to
choose the right type for a column.

Introduction
One of the key features of MySQL is its ability to handle various data types. Data
types define the type of data that can be stored in a particular column of a table.
Each data type has its characteristics, such as size, precision, and range, which
determine the kind of data that can be stored in that column and that is why it is
very important to choose the right data type for our table columns. When we create
a table, we need to specify a name for the table and a data type that not only tells us
and defines the kind of data that can be stored in the table column but also tells us
what influence it may have on the database efficiency and performance.
We can define the data type in MySQL with the following characteristics:

 The type of data (fixed or variable) it represents.


 The storage space it requires is based on whether the values are a fixed-
length or variable length.
 If the values that it represents can be indexed or not.
 How does MySQL compare the values of a specific data type?

As we already discussed, MySQL supports various data types such as numerical,


string, time and data, and many more. Let us try to understand each of these data
types in detail.

MySQL Data Types


Data Types define what kind of data you will store in a column and how different
SQL operations would be performed on that column.

We can broadly define the different data types in MySQL in five categories.

 String Data Types


 Numeric Data Types
 Date and Time Data Types
 Spatial Data types
 The JSON Data Type

String Data Types


In MySQL, the String Data Types are mostly used to store data as long strings of
text.

The MySQL String Data Types can be divided into these 6 categories:

 TEXT
 BLOB
 CHAR and VARCHAR
 BINARY and VARBINARY
 ENUM
 SET

The following table summarizes each string data type in MySQL and will give you
a basic understanding of each of them.
Data Type Maximum Size Description
Stores fixed-length strings
with a length of up to 255
characters. If the length is
CHAR(size) 255 characters
less than 255, then the
remaining space is padded
with spaces.
Stores variable-length strings
VARCHAR(size) 255 characters with a length of up
to 255 characters.
Stores a small text string
TINYTEXT(size) 255 characters with a length of up to 255
characters.
Stores a large text string with
TEXT(size) 65,535 characters a length of up to 65,535
characters.
Stores a medium text string
MEDIUMTEXT(size) 16,777,215 characters with a length of up to
16,777,215 characters.
Stores a very large text string
LONGTEXT(size) 4GB or 4,294,967,295 characters with a length of up to 4GB or
4,294,967,295 characters.
Stores fixed-length binary
strings with a length of up
to 255 characters. If the
BINARY(size) 255 characters
length is less than 255, then
the remaining space is
padded
Stores variable-length binary
VARBINARY(size) 255 characters strings with a length of up to
255 characters.
Stores a value from a
predefined list of values.
ENUM 65,535 values Each value is assigned a
numeric index from 1 to
65,535.
Stores one or more values
SET 64 members from a predefined list of up
to 64 members.

Text Data type

The TEXT data type has a storage capacity that ranges from 1 byte to 4 GB and
contrary to numeric data types, the TEXT data type in the table column does not
require you to provide a length.

The four TEXT data types in MySQL are TINYTEXT, TEXT, MEDIUMTEXT,
and LONGTEXT.
BLOB Datatype

The BLOB data types are binary strings as opposed to the non-binary string data
type, TEXT. Binary media files such as audio or video links, photos, or files, can
be stored using the BLOB data type in MySQL, which stands for a binary large
object data type.

Data Type Syntax Maximum Size


TINYBLOB It can hold a maximum size of 255 bytes.
BLOB(size) It can hold a maximum size of 65,535 bytes.
MEDIUMBLOB It can hold a maximum size of 16,777,215 bytes.
LONGBLOB It can hold a maximum size of 4 GB or 4,294,967,295 bytes.

CHAR and VARCHAR datatype

In MySQL, non-binary strings with fixed lengths up to 255 characters can store in
the CHAR data type, on the other hand, non-binary strings with variable lengths up
to 65535 characters can be stored in the VARCHAR data type.

When adding a column, you must specify a size parameter in characters (in
brackets) for both data types. The size option specifies the minimum and maximum
column sizes for CHAR and VARCHAR data types, respectively.

BINARY and VARBINARY datatype

BINARY and VARBINARY data types are quite similar to the CHAR and
VARCHAR data types, but they differ in a few ways. Binary strings are stored in
the variables BINARY and VARBINARY, whose length is expressed in bytes.

ENUM Datatype

MySQL ENUM data types represent the strings with enumeration values. With
ENUM, you can specify a list of predetermined values and then select from it. You
will receive an empty string if you add an invalid value that is not on the list.

SET datatype

The MySQL SET data types enable you to store one or more values that you
provided in a list of preset values when creating a table, separated by commas.

Numeric Data Types


In MySQL, there are several numeric data types that can be used to store numerical
values with varying levels of precision and range. Here are some of the most
common numeric data types in MySQL:

 TINYINT
 SMALLINT
 INT
 MEDIUMINT
 BIGINT
 DECIMAL
 FLOAT
 DOUBLE
 BIT
 BOOL
 BOOLEAN
 T
 he following table summarizes each numeric data type in MySQL and will
give you a basic understanding of each of them.

Data
Syntax Description
Type
A small-sized integer that can be signed or unsigned. If signed, the
allowable range is
from −2(n−1)−2(n−1) to 2(n−1)−12(n−1)−1. If unsigned,
the allowable range is from 0 to 2n−10 to 2n−1. The "n"
parameter specifies the maximum display width in digits and can
range from 1 to 3. TINYINT requires 1 byte for storage.
A larger-sized integer that can be signed or
unsigned. If signed, the allowable range is
from −2(n−1) to 2(n−1)−1
MEDIUMINT MEDIUMINT(n)
2(n−1)−1. If unsigned, the allowable range is
TINYIN TINYINT(n from 0 to 2n−10 to 2n−1. The "n" parame
T ) specifies the maximum display width in digits an
can range from 1 to 9. MEDIUMINT
requires 3 bytes for storage.
A normal-sized integer that can be signed or
unsigned. If signed, the allowable range is
from −2(n−1) to 2(n−1)−1
INT INT(n)
2(n−1)−1. If unsigned, the allowable range is
from 0 to 2n−10 to 2n−1. The "n" parame
specifies the maximum display width in digits an
can range from 1 to 11. INT requires
storage.
SMALLI SMALLIN A medium-sized integer that can be signed or unsigned. If signed, the
NT T(n) allowable range is from -2^(n-1) to
Data
Syntax Description
Type
A large-sized integer that can be signed or unsigned. If signed, the
allowable range is from −2(n−1) to 2(n−1)−1−2(n−1) to 2(n−1)−1. If
BIGINT BIGINT(n) unsigned, the allowable range is from 0 to 2n−10 to 2n−1. The "n"
parameter specifies the maximum display width in digits and can
range from 1 to 20. BIGINT requires 8 bytes for storage.
A floating-point number that cannot be unsigned. The "m" parameter
specifies the maximum display width in digits and the "d" parameter
FLOAT(m,
FLOAT specifies the number of digits after the decimal point. If not specified,
d)
"m" defaults to 10, and "d" defaults to 2. FLOAT can store up
to 24 decimal places and requires 4 bytes for storage.

A floating-point number that cannot be unsigned. The


"m" parameter specifies the maximum display width in
digits and the "d" parameter specifies the number of
FLOAT FLOAT(m,d)
digits after the decimal point. If not specified, "m"
defaults to 10, and "d" defaults to 2. FLOAT can store
up to 24 decimal places and requires 4 bytes for storage.
A double-precision floating-point number that cannot be
unsigned. The "m" parameter specifies the maximum
display width in digits and the "d" parameter specifies
DOUBLE DOUBLE(m,d) the number of digits after the decimal point. If not
specified, "m" defaults to 16, and "d" defaults to 4.
DOUBLE can store up to 53 decimal places and
requires 8 bytes
An unpacked floating-point number that cannot be
unsigned. The "m" parameter specifies the maximum
display width in digits and the "d" parameter specifies
DECIMAL DECIMAL(m,d)
the number of digits after the decimal point. Both
parameters are required. DECIMAL stores each digit of
the number as one byte,
Used for storing bit values into a table column. The
number of bits per value is determined by the value of
BIT BIT(m) m, which can range from 1 to 64. It requires 1, 2, 3, 4, 5,
6, 7, or 8 bytes, depending on the number of bits
specified by m.
Used only for the true and false conditions. It is
BOOL BOOL considered a numeric value, with 1 being true
and 0 being false. It requires 1 byte for storage.
Similar to BOOL, used only for the true and false
BOOLEAN BOOLEAN condition. It is considered a numeric value, with 1 being
true and 0 being false. It requires 1 byte for storage.

Integer Data Types


Integer data types are used to store whole numbers without any fractions. There are
different integer data types available in MySQL, such as TINYINT, SMALLINT,
INT, MEDIUMINT, and BIGINT.

UNSIGNED integer data types allow only zero and positive numbers, while
SIGNED integer data types allow zero, positive, and negative numbers.

Boolean data types

Boolean data types, unlike integer data types, can only store true or false values. In
MySQL, boolean values are converted into integer data types (TINYINT),
where 0 represents false and 1 represents true.

Float data types


Float data types are used to represent single-precision numeric values, which are
approximate values that require 4 bytes for storage. They can be set as
either SIGNED or UNSIGNED, and have a minimum and maximum storage size
depending on their attribute. If you're working with MySQL version 8.0.17 or later,
note that UNSIGNED is deprecated for the FLOAT and DOUBLE data types.

Double data types

Double data types are used to represent double-precision numeric values, which are
also approximate but require 8 bytes for storage. Similar to float data types, they
can be set as either SIGNED or UNSIGNED and have a minimum and maximum
storage size depending on their attribute.

Decimal data types


Decimal data types are used to store exact and fixed numeric values. The precision
and scale of the data type can be set when creating a table column using
the DECIMAL(p,s) syntax.

BIT data type


Lastly, the BIT data type is used to store binary values and can only accept values
of either 0 or 1. The range of bit values for the column can be set, with the default
value being 1 if no range is specified.

Date and Time Data Types


MySQL provides different data types for managing date and time information in
databases.

These data types are:

 DATE
 TIME
 DATETIME
 TIMESTAMP
 YEAR

The following table summarizes the usage, data type format, and range of each
type:

Type Usage Data Type Format Range


Stores only date
YYYY-MM-DD (year-month- From ‘1000-01-01’
DATE information in
day) to ‘9999-12-31’
the table column
Displays only From ‘-838:59:59’
TIME HH:MM:SS (hours:minutes)
time to ‘838:59:59’
Stores both date From ‘1000-01-01
YYYY-MM-DD HH:MM (year-
DATETIME and time in the 00:00:00’ to ‘9999-
month-day hours:minutes)
column 12-31 23:59:59’
From ‘1970-01-01
Stores both date YYYY-MM-DD
00:00:01’ UTC to
TIMESTAMP and time values HH:MM:SS (year-month-day
‘2038-01-19
in the column hours:minutes)
03:14:07’ UTC
Stores only year
YEAR values in the YYYY (year) From ‘1901’ to
column
Stores only year
YEAR values in the YYYY (year) From ‘1901’ to ‘2155’
column

Spatial Data Types


MySQL supports spatial data types that store geometry and geography values in
the table column. These data types include GEOMETRY, POINT, LINESTRING,
POLYGON, MULTIPOINT, MULTILINESTRING, MULTIPOLYGON, and
GEOMETRYCOLLECTION. Each data type is used to store a specific type of
spatial data.

Here is a new table that describes spatial data type:

Type Description Examples


Stores any type of geometry A point, line, or polygon with
GEOMETRY
value any number of vertices.
Stores a single X and Y A single point with an X and Y
POINT
coordinate value coordinate.
Stores a set of points that A line that connects two or
LINESTRING
form a curve more points.
POLYGON Stores a set of points in the A polygon with at least three
Type Description Examples
multisided geometry points.
Stores a set of multiple point Two or more points that are
MULTIPOINT
values not connected.
Stores a set of multiple Two or more line segments
MULTILINESTRING
LINESTRING values that are not connected.
Stores a set of multiple Two or more polygons that are
MULTIPOLYGON
POLYGON values not connected.

Stores a set of multiple Two or more geometries of


GEOMETRYCOLLECTION
GEOMETRY values. different types.

JSON Data Type


MySQL has introduced JSON data types that store JSON documents in the JSON
column starting from version 5.7.8. JSON format provides a quicker way to access
the document elements by searching values within the document with a key or
array index. It also optimizes storage and enhances performance. JSON format has
a built-in validation feature that can identify and flag invalid values. However, the
maximum size of the JSON document is limited to 1GB.

You might also like