PHP Notes Unit 4
PHP Notes Unit 4
UNIT 4:
Class &Objects in PHP: What is Class & Object, Creating and accessing a Class &Object, Object
properties, object methods, Overloading, inheritance, Constructor and Destructor
Form Handling: Creating HTML Form, Handling HTML Form data in PHP
Database Handling Using PHP with MySQL: Introduction to MySQL: Database terms, Data
Types
Classes:
A class is a blueprint or template used to create objects. It specifies the
properties(attributes) and methods(functions) that the class’s object will possess. The class
keyword is used in PHP to define a class.
Syntax:
class class__name{
//properties
public $var1;
public $var2;
//Methods
public function funName(){
body
}
}
Ex:
<?php
class Person{
public $fname;
public $lname;
}
$p1 = new Person();
$p1->fname = “Suresh”;
$p1->lname = “M”;
$p1->sayHello();
?>
Note:
Properties: Variables that store data within an object
Methods: Functions that define the behavior of objects.
Constructors: Special method named __construct() that are automatically executed when
an object is created. They are used to initialize properties.
Destructors: : Special method named __destruct() that are automatically executed when
an object is destroyed. They are used to cleanup tasks.
Visibility: Keywords like public, private and protected control access to properties and
methods within and outside the class.
Inheritance: Classes can inherit properties and methods from one class to another class,
creating hierarchical structure.
Object:
Object is a real world entity. An object is a class instance. Objects are created based on
classes, and each object as its own set of properties as well as the ability to invoke the methods
described in the class. The new keyword is used to construct things.
An object is a type of class instance. You build objects based on classes, and each object
has its own set of properties and can call the methods described in the class. Using the new
keyword, you can build objects.
<?php
class Car{
//Properties
public $brand;
public $model;
//Methods
function set_brand($brand){
$this->brand==$brand;
}
function get_brand(){
return $this->brand;
}
}
$myCar=new Car();
$myCar->set_brand(“Kia”);
echo $myCar->get_brand();
?>
This class defines a Car object that has two properties (brand and model) and two methods
(set_brand() and get_brand()). The $this keyword refers to the current object and is used to access
its properties and methods.
Note:
$this keyword: Used within methods to refer to the current object.
Accessing properties and methods: Use the object’s name followed by the property or
method name and parenthesis for methods ($object->property, $object->method()).
<?php
class Person{
public $name;
public $age;
Creating Object:
Step 1: Use the new keyword:
$obj = new ClassName($arg1, $arg2);
// pass arguments if the constructor requires them
Ex:
<?php
class Person{
public $name;
public $age;
Use the public, private and protected keywords to control visibility of properties and
methods.
$this keyword refers to the current object within its methods.
Constructors are used to initialize object properties when it‘s created.
You can create multiple objects from the same class, each with its own state.
Object Properties:
Properties are variables declared within a class and assigned to particular objects within
that class. They store data that represents the object’s attributes or qualities. Each object has its
own set of properties with different values.
1. Declaring Properties:
Properties are declared within a class using the public, private or protected keywords.
class Person{
public $name;
private $age;
}
2. Accessing Properties:
Outside the class: Public properties can be accessed using the object name and the
arrow operator(->).
$per=new Person();
$per->name=”Bharat”;
echo $per->name;
private and protected properties cannot be accessed directly from the class.
Inside the class: All properties can be accessed using the $this keyword.
public function introduce(){
echo “Hello, my Name is “ . $this.name.”.\n”;
}
3. Visibility: PHP visibility is a concept that defines how the properties and methods of a
class can be accessed. There are three visibility keywords in PHP: public, private and
protected. They determine the scope and accessibility of the class members.
public: A public property or method can be accessed from anywhere, including the
same class, its subclasses and any internal code.
private: A private property or method can be accessed only from within the same
class that declared it. It is not visible to subclasses or external code.
protected: A protected property or method can be accessed from within the same
class and its subclasses, but not from external code.
4. Initializing Properties:
Constructors: Used to initialize properties when an object is created.
public function __construct($name, $age){
$this->name=$name;
$this->age=$age;
}
Object Methods:
Object methods are functions defined within a class in PHP. These methods represent the
activity or actions that class objects can carry out. Object methods are connected with a specific
instance of a class and can operate on the instance’s properties.
1. Declaring Methods:
Methods are declared within a class using the function keyword, followed by the method
name, parenthesis and optionally a visibility keyword.
class Person{
public function introduce(){
echo “Hello, my name is “ . $this->name.”.\n”;
}
}
2. Accessing Methods:
Methods are accessed using the object name, the arrow operator(->), and the method name
followed by parenthesis.
$per1=new Person();
$per1->introduce();
3. $this keyword:
Within a method, the $this keyword refers to the current object. I’s used to access the
object’s properties and call other methods of the same object.
public function getAge(){
return $this->age;
}
4. Visibility:
public methods: Can be accessed from anywhere.
Private methods: Can only be accessed from within the class itself.
Protected methods: Can be accessed from within the class an its subclasses.
Arguments and Return Values.
6. Special methods:
Constructors: ___construct() is used to initialize objects when they are created.
Destructors:___destruct() is used to perform cleanup tasks when an object is
destroyed.
Other magic methods: PHP has several other special methods with double
underscores that have specific behaviors(Ex: __toString(), __call(), __clone())
Overloading in PHP
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 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.
Example:
PHP
<?php
//
class GFG {
// 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]);
}
// Create an object
$obj = new GFG;
// Unset 'a'
unset($obj->a);
var_dump(isset($obj->a));
?>
Output:
Setting 'a' to '1'
Getting 'a: 1
Is 'a' set?
bool(true)
Unsetting 'a'
Is 'a' set?
bool(false)
1
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.
Example:
PHP
<?php
class GFG {
Output:
Calling object method 'runTest' in object context
Calling static method 'runTest' in static context
Inheritance:
It is a concept of accessing the features of one class from another class. If we inherit the
class features into another class, we can access both class properties. We can extend the features
of a class by using 'extends' keyword.
Inheritance is a way of extending the existing class functionality in the newly created class.
We can also add functionality to the newly created class apart from extending the base class
functionalities. When we inherit one class, we say an inherited class is a child class (sub-class),
which is called the parent class from which we inherit it. The parent class is also known as the
base class. This is the way that enables better management of the programming code and code
reusability. The idea behind using inheritance is all about better management of the code and the
code reusability.
Multiple Inheritance NO
1. Single Inheritance
PHP supports Single inheritance. Single inheritance is a concept in PHP in which only one class
can be inherited by a single class. We need to have two classes in between this process. One is the
base (parent) class, and the other is the child class. Let’s understand the same with an example. It
is popularly known as simple inheritance. This type of inheritance in PHP language remains the
same as JAVA, C++, etc.
Ex:
<?php
class MyAccess {
var $var = "This is first var";
protected $fist_name;
// simple class method
function returnVar() {
echo $this->fist_name;
}
function set_fist_name($set_this){
$this->fist_name = $set_this;
}
}
class child extends MyAccess {
function setVal($set_this){
$this->fist_name = $set_this;
}
function getVal(){
echo $this->fist_name;
}
}
$obj1 = new child();
$obj1->setVal("Jai Shre");
$obj1->getVal();
?>
MyAccess is the parent, and the child is the name of the child’s class.
Output:
Jai Shre
2. Multilevel Inheritance
PHP supports Multilevel Inheritance. In this type of inheritance, we will have more than 2
classes. In this type of inheritance, a parent class will be inherited by a child class then that child
class will be inherited by the child class. This type of inheritance in PHP language remains the
same as in C++ etc.
Code:
<?php
class ParentClass {
var $var = "This is first var";
public $fist_name;
// simple class method
function returnVar() {
echo $this->fist_name;
}
function set_fist_name($set_this){
$this->fist_name = $set_this;
}
}
class child_1 extends ParentClass {
function setVal($set_this){
$this->fist_name = $set_this;
}
function getVal(){
echo "Extended By Parent Class -". $this->fist_name;
}
}
class child_2 extends child_1 {
function setVal($set_this){
$this->fist_name = $set_this;
}
function getVal(){
echo "Extended By child 1 - ".$this->fist_name;
}
}
$obj1 = new child_1();
$obj1->setVal("This is first inherited class");
$obj1->getVal();
echo "<br/><br/>";
$obj2 = new child_2();
$obj2->setVal("This is second inherited class");
$obj2->getVal();
?>
3. Hierarchical Inheritance
PHP supports Hierarchical inheritance. Hierarchical inheritance is the type of inheritance in
which a program consists of a single parent and more than one child class. Let’s understand the
same with this example. This type of inheritance in PHP language remains the same as JAVA,
C++, etc.
Ex:
<?php
class ParentClass {
4. Multiple Inheritance:
Multiple Inheritance is the property of the Object Oriented Programming languages in which
child class or sub class can inherit the properties of the multiple parent classes or super classes.
PHP doesn’t support multiple inheritance but by using Interfaces in PHP or using Traits in PHP
instead of classes, we can implement it.
Traits (Using Class along with Traits): The trait is a type of class which enables multiple
inheritance. Classes, case classes, objects, and traits can all extend no more than one class but
can extend multiple traits at the same time.
Syntax:
class child_class_name extends parent_class_name {
use trait_name;
...
...
child_class functions
}
Example:
<?php
// Class Geeks
class Geeks {
public function sayhello() {
echo "Hello";
}
}
// Trait forGeeks
trait forGeeks {
public function sayfor() {
echo " Geeks";
}
}
echo "\nGeeksforGeeks";
}
}
Output:
Hello Geeks
GeeksforGeeks
In the above program “traits” has been used along with parent class. There is “class” named
“Geeks” which contains function sayhello() and a “trait” named “forGeeks” which contains
function geeksforgeeks() and there is child class named “Sample” and we are creating the object
of this class named “test” and using it we are invoking all the functions of a class and a trait.
Traits (Using Multiple Traits): Multiple Traits can be inserted into a class by listing them in
the use statement, separated by commas.
<?php
class A {
public function insideA() {
echo "I am in class A";
}
}
interface B {
public function insideB();
}
function insideB() {
echo "\nI am in interface";
}
Output:
I am in class A
I am in interface
I am in inherited class
In the above program Interface “B” has been used along with the class “A” to implement multiple
inheritance. The important point to remember is, it can’t define the function inside interface, it
should be defined inside the child class “Multiple”. We are invoking all the functions using the
child class (Multiple) object named “geeks”.
Interface (Using Multiple Interface):
Syntax:
class child_class_name implements interface_name1, interface_name2, ...
Example:
<?php
interface C {
public function insideC();
}
interface B {
public function insideB();
}
Output:
I am in interface C
I am in interface B
I am in inherited class
In the above program multiple interfaces has been used to implement multiple inheritance. In
above example there are two interfaces named “B” and “C” those are playing the role of the base
classes and there is child class named “Multiple” and we are invoking all the functions using its
object named “geeks”.
Final Keyword
The final keyword prevents child classes from overriding a method or constant by prefixing the
definition with final. If the class itself is being defined final then it cannot be extended.
<?php
class BaseClass {
public function test() {
echo "BaseClass::test() called\n";
}
}
}
// Results in Fatal error: Cannot override final method BaseClass::moreTesting()
?>
Constructor:
A constructor allows you to initialize an object's properties upon creation of the object.
If you create a __construct() function, PHP will automatically call this function when you create
an object from a class. Notice that the construct function starts with two underscores (__)!
Ex:
<?php
class Fruit {
public $name;
public $color;
A destructor is called when the object is destructed or the script is stopped or exited.
If you create a __destruct() function, PHP will automatically call this function at the end of the
script. Notice that the destruct function starts with two underscores (__)!
Ex:
<?php
class Fruit {
public $name;
public $color;
An HTML form is a section of a document which contains controls such as text fields, password
fields, checkboxes, radio buttons, submit button, menus etc.
An HTML form facilitates the user to enter data that is to be sent to the server for processing such
as name, email address, password, phone number, etc..
HTML forms are required if you want to collect some data from of the site visitor.
The most important process in any dynamic Website is handling an HTML form with PHP. There
are two phases involved, first, create the HTML form, and then create the associated PHP script
that will receive and handle the form data.
In terms of PHP, the most important attribute of the form tag is action, which dictates to
which page the form data will be sent to. The second attribute method.
Choosing a Method:
A form’s method attribute specifies how data is transferred to the handling page. The terms get
and post relates to the HTTP (Hyper Text Transfer Protocol) technique that will be utilized. The
GET method send the submitted data as a series of name-value pairs appended to the URL to the
receiving page.
In general, GET is used to request information, such as specific record from a database or
the results of a search (searches virtually always utilize GET). When an action is expected, like an
changing aa database record or sending an email, the POST method is utilized.
Tag Description
Ex:
<!DOCTYPE html PUBLIC "-//W3C// DTD XTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-trasitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Form Tagg Elements</title>
<style type="text/css" title="text/css" media="all">
label{
font-weight:bold;
color:#300ACC;
}
</style>
</head>
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name=$_REQUEST['name'];
$email=$_REQUEST['email'];
$comments=$_REQUEST['comments'];
?>
2. Processing Data:
Retrieving Values:
$name=$_POST[‘name’]; retrieves the value of the “name” field
Validation:
Ensure data is valid and secure using techniques like:
Type checking (numeric or numbers)
Regular expressions (for ex: email)
Storing or using Data:
Save data to database.
Send it via email.
Display it on a web page.
Use it for further processing
3. Providing Feedback:
Confirmation Messages: Inform users about successful submission
Error Messages: Indicate any errors or missing fields.
Clear Information: Gide users to correct any issues.
Post request is widely used to submit form that have large amount of data such as file upload,
image upload, login form, registration form etc.
The data passed through post request is not visible on the URL browser so it is secured. You can
send large amount of data through post request.
formpost.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html">
<title>Form Feedback</title>
</head>
<body>
<form action="formpost.php" method="post">
Name:<input type="text" name="name"><br>
Email:<input type="text" name="email"><br>
<input type="submit" ><br>
</form>
</body>
</html>
formpost.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html">
<title>Form Feedback</title>
</head>
<body>
Welcome<?php echo $_POST["name"];?><br>
Your email address is <?php echo $_POST["email"];?><br>
</body>
</html>
formget.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html">
<title>Form Feedback</title>
</head>
<body>
<form action="formget.php" method="get">
Name:<input type="text" name="name"><br>
Email:<input type="text" name="email"><br>
<input type="submit" ><br>
</form>
</body>
</html>
formget.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html">
<title>Form Feedback</title>
</head>
<body>
Welcome<?php echo $_GET["name"];?><br>
Your email address is <?php echo $_GET["email"];?><br>
</body>
</html>
An HTML form contains various input fields such as text box, checkbox, radio buttons, submit
button, and checklist, etc. These input fields need to be validated, which ensures that the user has
entered information in all the required fields and also validates that the information provided by
the user is valid and correct.
There is no guarantee that the information provided by the user is always correct. PHP validates
the data at the server-side, which is submitted by HTML form. You need to validate a few things:
1. Empty String
2. Validate String
3. Validate Numbers
4. Validate Email
5. Validate URL
6. Input length
Empty String
The code below checks that the field is not empty. If the user leaves the required field empty, it
will show an error message. Put these lines of code to validate the required field.
if (emptyempty ($_POST["name"])) {
$errMsg = "Error! You didn't enter the Name.";
echo $errMsg;
} else {
$name = $_POST["name"];
}
Validate String
The code below checks that the field will contain only alphabets and whitespace, for example -
name. If the name field does not receive valid input from the user, then it will show an error
message:
Validate Number
The below code validates that the field will only contain a numeric value. For example - Mobile
no. If the Mobile no field does not receive numeric data from the user, the code will display an
error message:
Validate Email
A valid email must contain @ and . symbols. PHP provides various methods to validate the email
address. Here, we will use regular expressions to validate the email address.
The below code validates the email address provided by the user through HTML form. If the field
does not contain a valid email address, then the code will display an error message:
The input length validation restricts the user to provide the value between the specified range, for
Example - Mobile Number. A valid mobile number must have 10 digits.
The given code will help you to apply the length validation on user input:
Validate URL
The below code validates the URL of website provided by the user via HTML form. If the field
does not contain a valid URL, the code will display an error message, i.e., "URL is not valid".
ADVERTISEMENT
$websiteURL = $_POST["website"];
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-
9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "URL is not valid";
echo $websiteErr;
} else {
echo "Website URL is: " .$websiteURL;
}
The below code validates that the user click on submit button and send the form data to the server
one of the following method - get or post.
if (isset ($_POST['submit']) {
echo "Submit button is clicked.";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
echo "Data is sent using POST method ";
}
} else {
echo "Data is not submitted";
}
Note: Remember that validation and verification both are different from each other.
Now we will apply all these validations to an HTML form to validate the fields. Thereby you can
learn in detail how these codes will be used to validation form.
Create a registration form using HTML and perform server-side validation. Follow the below
instructions as given:
<!DOCTYPE html>
<html>
<head>
<style>
.error {color: #FF0001;}
</style>
</head>
<body>
<?php
// define variables to empty values
$nameErr = $emailErr = $mobilenoErr = $genderErr = $websiteErr = $agreeErr = "";
$name = $email = $mobileno = $gender = $website = $agree = "";
//String Validation
if (emptyempty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = input_data($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only alphabets and white space are allowed";
}
}
//Email Validation
if (emptyempty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = input_data($_POST["email"]);
// check that the e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
//Number Validation
if (emptyempty($_POST["mobileno"])) {
$mobilenoErr = "Mobile no is required";
} else {
$mobileno = input_data($_POST["mobileno"]);
// check if mobile no is well-formed
if (!preg_match ("/^[0-9]*$/", $mobileno) ) {
$mobilenoErr = "Only numeric value is allowed.";
}
//check mobile no length should not be less and greator than 10
if (strlen ($mobileno) != 10) {
$mobilenoErr = "Mobile no must contain 10 digits.";
}
}
//URL Validation
if (emptyempty($_POST["website"])) {
$website = "";
} else {
$website = input_data($_POST["website"]);
// check if URL address syntax is valid
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-
9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}
//Checkbox Validation
if (!isset($_POST['agree'])){
$agreeErr = "Accept terms of services before submit.";
} else {
$agree = input_data($_POST["agree"]);
}
}
function input_data($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>Registration Form</h2>
<span class = "error">* required field </span>
<br><br>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" >
Name:
<input type="text" name="name">
<span class="error">* <?php echo $nameErr; ?> </span>
<br><br>
E-mail:
<input type="text" name="email">
<span class="error">* <?php echo $emailErr; ?> </span>
<br><br>
Mobile No:
<input type="text" name="mobileno">
<span class="error">* <?php echo $mobilenoErr; ?> </span>
<br><br>
Website:
<input type="text" name="website">
<span class="error"><?php echo $websiteErr; ?> </span>
<br><br>
Gender:
<input type="radio" name="gender" value="male"> Male
<input type="radio" name="gender" value="female"> Female
<?php
if(isset($_POST['submit'])) {
if($nameErr == "" && $emailErr == "" && $mobilenoErr == "" && $genderErr == "" && $
websiteErr == "" && $agreeErr == "") {
echo "<h3 color = #FF0001> <b>You have sucessfully registered.</b> </h3>";
echo "<h2>Your Input:</h2>";
echo "Name: " .$name;
echo "<br>";
echo "Email: " .$email;
echo "<br>";
echo "Mobile No: " .$mobileno;
echo "<br>";
echo "Website: " .$website;
echo "<br>";
echo "Gender: " .$gender;
} else {
echo "<h3> <b>You didn't filled up the form correctly.</b> </h3>";
}
}
?>
</body>
</html>
When the above code runs on a browser, the output will be like the screenshot below:
Fill the registration form and click on the Submit button. If all required information is provided
correctly, the output will be displayed on the same page below the submit button. See the
screenshot below:
MySQL is a relational database management system based on the Structured Query Language,
which is the popular language for accessing and managing the records in the database. MySQL is
open-source and free software under the GNU license. It is supported by Oracle Company.
DATABASE TERMS:
1. Database - A database is a collection of tables, with related data.
2. Table - A table is a matrix with data. A table in a database looks like a simple spreadsheet.
3. Column - One column (data element) contains data of one and the same kind, for example,
the column postcode.
4. Row - A row (= tuple, entry or record) is a group of related data, for example, the data of
one subscription.
5. Redundancy - Storing data twice in more than one tables, redundantly to make the system
faster.
6. Primary Key - A primary key is unique. A key value can not occur twice in one table.
With a key, you can only find one row. A table will have only one Primary Key
7. Unique Key - A unique key is a combination of one or more columns which can uniquely
identify a row in the table. That combination cannot occur more than once in one table
excluding rows having NULL values in key columns. A table can have more than one
unique key.
8. Compound Key - A compound key (composite key) is a key that consists of multiple
columns because one column is not sufficiently unique. Another term for the unique key
which has more than one column.
9. Foreign Key - A foreign key is a linking pin between two tables.
10. Index - An index in a database resembles an index at the back of a book.
11. Referential Integrity - Referential Integrity makes sure that a foreign key value always
points to an existing row.
A Data Type specifies a particular type of data, like integer, floating points, Boolean, etc. It also
identifies the possible values for that type, the operations that can be performed on that type, and
the way the values of that type are stored. In MySQL, each database table has many columns and
contains specific data types for each column.
We can determine the data type in MySQL with the following characteristics:
MySQL supports a lot number of SQL standard data types in various categories. It uses many
different data types that can be broken into the following categories: numeric, date and time, string
types, spatial types, and JSON data types.
MySQL has all essential SQL numeric data types. These data types can include the exact numeric
data types (For example, integer, decimal, numeric, etc.), as well as the approximate numeric data
types (For example, float, real, and double precision). It also supports BIT datatype to store bit
values. In MySQL, numeric data types are categories into two types, either signed or unsigned
except for bit data type.
The following table contains all numeric data types that support in MySQL:
TINYINT It is a very small integer that can be signed or unsigned. If signed, the allowable
range is from -128 to 127. If unsigned, the allowable range is from 0 to 255. We
can specify a width of up to 4 digits. It takes 1 byte for storage.
SMALLINT It is a small integer that can be signed or unsigned. If signed, the allowable range
is from -32768 to 32767. If unsigned, the allowable range is from 0 to 65535. We
can specify a width of up to 5 digits. It requires 2 bytes for storage.
MEDIUMINT It is a medium-sized integer that can be signed or unsigned. If signed, the allowable
range is from -8388608 to 8388607. If unsigned, the allowable range is from 0 to
16777215. We can specify a width of up to 9 digits. It requires 3 bytes for storage.
INT It is a normal-sized integer that can be signed or unsigned. If signed, the allowable
range is from -2147483648 to 2147483647. If unsigned, the allowable range is from
0 to 4294967295. We can specify a width of up to 11 digits. It requires 4 bytes for
storage.
BIGINT It is a large integer that can be signed or unsigned. If signed, the allowable range is
from -9223372036854775808 to 9223372036854775807. If unsigned, the
allowable range is from 0 to 18446744073709551615. We can specify a width of
up to 20 digits. It requires 8 bytes for storage.
FLOAT(m,d) It is a floating-point number that cannot be unsigned. You can define the display
length (m) and the number of decimals (d). This is not required and will default to
10,2, where 2 is the number of decimals, and 10 is the total number of digits
(including decimals). Decimal precision can go to 24 places for a float type. It
requires 2 bytes for storage.
go to 53 places for a double. Real is a synonym for double. It requires 8 bytes for
storage.
BIT(m) It is used for storing bit values into the table column. Here, M determines the
number of bit per value that has a range of 1 to 64.
BOOL It is used only for the true and false condition. It considered numeric value 1 as true
and 0 as false.
This data type is used to represent temporal values such as date, time, datetime, timestamp, and
year. Each temporal type contains values, including zero. When we insert the invalid value,
MySQL cannot represent it, and then zero value is used.
The following table illustrates all date and time data types that support in MySQL:
YEAR[(2|4)] Year value as 2 digits or 4 digits. The default is 4 digits. It takes 1 byte for
storage.
The string data type is used to hold plain text and binary data, for example, files, images, etc.
MySQL can perform searching and comparison of string value based on the pattern matching such
as LIKE operator, Regular Expressions, etc.
The following table illustrates all string data types that support in MySQL:
CHAR(size) It can have a maximum size of Here size is the number of characters
255 characters. to store. Fixed-length strings. Space
padded on the right to equal size
characters.
VARCHAR(size) It can have a maximum size of Here size is the number of characters
255 characters. to store. Variable-length string.
TINYTEXT(size) It can have a maximum size of Here size is the number of characters
255 characters. to store.
MEDIUMTEXT(size) It can have a maximum size of Here size is the number of characters
16,777,215 characters. to store.
LONGTEXT(size) It can have a maximum size of Here size is the number of characters
4GB or 4,294,967,295 characters. to store.
BINARY(size) It can have a maximum size of Here size is the number of binary
255 characters. characters to store. Fixed-length
strings. Space padded on the right to
equal size characters.
(introduced in MySQL 4.1.2)
VARBINARY(size) It can have a maximum size of Here size is the number of characters
255 characters. to store. Variable-length string.
(introduced in MySQL 4.1.2)
BLOB in MySQL is a data type that can hold a variable amount of data. They are categories into
four different types based on the maximum length of values can hold.
The following table shows all Binary Large Object data types that support in MySQL:
It is a special kind of data type which is used to hold various geometrical and geographical values.
It corresponds to OpenGIS classes. The following table shows all spatial types that support in
MySQL:
GEOMETRY It is a point or aggregate of points that can hold spatial values of any
type that has a location.
LINESTRING It is a curve that has one or more point values. If it contains only two
points, it always represents Line.
MySQL provides support for native JSON data type from the version v5.7.8. This data type allows
us to store and access the JSON document quickly and efficiently.
The JSON data type has the following advantages over storing JSON-format strings in a string
column: