Unit 3 PHP
Unit 3 PHP
MySQL:
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.
What is Database?
It is very important to understand the database before learning MySQL. A database is an
application that stores the organized collection of records. It can be accessed and manage
by the user very easily. It allows us to organize data into tables, rows, columns, and indexes
to find the relevant information very quickly.
What is MySQL?
MySQL is currently the most popular database management system software used for
managing the relational database. It is open-source database software, which is
supported by Oracle Company. It is fast, scalable, and easy to use database management
system in comparison with Microsoft SQL Server and Oracle Database. It is commonly
used in conjunction with PHP scripts for creating powerful and dynamic server-side or
web-based enterprise applications.
The core of the MySQL database is the MySQL Server. This server is available as a separate
program and responsible for handling all the database instructions, statements, or
commands. The working of MySQL database with MySQL Server are as follows:
1. MySQL creates a database that allows you to build many tables to store and manipulate
data and defining the relationship between each table.
2. Clients make requests through the GUI screen or command prompt by using specific SQL
expressions on MySQL.
3. Finally, the server application will respond with the requested expressions and produce
the desired result on the client-side.
A client can use any MySQL GUI. But, it is making sure that your GUI should be lighter and
user-friendly to make your data management activities faster and easier. Some of the
most widely used MySQL GUIs are MySQL Workbench, SequelPro, DBVisualizer, and the
Navicat DB Admin Tool. Some GUIs are commercial, while some are free with limited
functionality, and some are only compatible with MacOS. Thus, you can choose the GUI
according to your needs.
MySQL Create Database
A database is used to store the collection of records in an organized form. It allows us to
hold the data into tables, rows, columns, and indexes to find the relevant information
frequently. We can access and manage the records through the database very easily.
MySQL implements a database as a directory that stores all files in the form of a table.
MySQL Workbench
It is a visual database designing or GUI tool used to work with database architects,
developers, and Database Administrators. This visual tool supports SQL development,
data modeling, data migration, and comprehensive administration tools for server
configuration, user administration, backup, and many more. It allows us to create new
physical data models, E-R diagrams, and SQL development (run queries, etc.).
The SQL CREATE DATABASE statement is used to create new SQL database.
Syntax:
Basic syntax of CREATE DATABASE statement is as follows:
CREATE DATABASE DatabaseName;
Always database name should be unique within the RDBMS.
Example:
If you want to create new database <testDB>, then CREATE DATABASE statement would
be as follows:
SQL> CREATE DATABASE testDB;
Make sure you have admin privilege before creating any database. Once a database is
created, you can check it in
the list of databases as follows:
SQL> SHOW DATABASES;
+--------------------+
| Database |
+--------------------+
| information_schema |
| AMROOD |
| TUTORIALSPOINT |
| mysql |
| orig |
| test |
| testDB |
+--------------------+
INSERT Query
The SQL INSERT INTO Statement is used to add new rows of data to a table in the
database.
Syntax:
There are two basic syntaxes of INSERT INTO statement as follows:
INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)]
VALUES (value1, value2, value3,...valueN);
Here, column1, column2,...columnN are the names of the columns in the table into
which you want to insert data.
You may not need to specify the column(s) name in the SQL query if you are adding
values for all the columns of the table. But make sure the order of the values is in the
same order as the columns in the table. The SQL INSERT INTO syntax would be as
follows:
INSERT INTO TABLE_NAME VALUES (value1,value2,value3,...valueN);
Example:
Following statements would create six records in CUSTOMERS table:
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00 );
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (2, 'Khilan', 25, 'Delhi', 1500.00 );
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (3, 'kaushik', 23, 'Kota', 2000.00 );
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (4, 'Chaitali', 25, 'Mumbai', 6500.00 );
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (5, 'Hardik', 27, 'Bhopal', 8500.00 );
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (6, 'Komal', 22, 'MP', 4500.00 );
You can create a record in CUSTOMERS table using second syntax as follows
INSERT INTO CUSTOMERS
VALUES (7, 'Muffy', 24, 'Indore', 10000.00 );
All the above statements would produce the following records in CUSTOMERS table:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
SELECT Query
SQL SELECT Statement is used to fetch the data from a database table which returns
data in the form of result table. These result tables are called result-sets.
Syntax:
The basic syntax of SELECT statement is as follows:
SELECT column1, column2, columnN FROM table_name;
Here, column1, column2...are the fields of a table whose values you want to fetch. If you
want to fetch all the fields available in the field, then you can use the following syntax:
SELECT * FROM table_name;
Example:
Consider the CUSTOMERS table having the following records:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Following is an example, which would fetch ID, Name and Salary fields of the customers
available in CUSTOMERS table:
SQL> SELECT ID, NAME, SALARY FROM CUSTOMERS;
This would produce the following result:
+----+----------+----------+
| ID | NAME | SALARY |
| 1 | Ramesh | 2000.00 |
| 2 | Khilan | 1500.00 |
| 3 | kaushik | 2000.00 |
| 4 | Chaitali | 6500.00 |
| 5 | Hardik | 8500.00 |
| 6 | Komal | 4500.00 |
| 7 | Muffy | 10000.00 |
+----+----------+----------+
If you want to fetch all the fields of CUSTOMERS table, then use the following query:
SQL> SELECT * FROM CUSTOMERS;
This would produce the following result:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
The following table contains the items bought by several people last week:
Order By
Let's see the following query:
as you can see the fiels have been ordered by the price. The default order is ascending. If you want
to specify how the data is ordered, write either ASC or DESC at the end of your query
Example:
will give the same table, but starting with the pillow.
GROUP BY CLAUSE
The SQL GROUP BY clause is used in collaboration with the SELECT statement to
arrange identical data into groups.
The GROUP BY clause follows the WHERE clause in a SELECT statement and
precedes the ORDER BY clause.
Syntax:
The basic syntax of GROUP BY clause is given below. The GROUP BY clause must
follow the conditions in the WHERE clause and must precede the ORDER BY
clause if one is used.
SELECT column1, column2
FROM table_name
WHERE [ conditions ]
GROUP BY column1, column2
ORDER BY column1, column2
The group by statement, as said before, is especially useful for aggregating, meaning to apply some
function. Let's see an example:
SELECT cust_id, SUM(total_price) FROM shopping GROUP BY cust_id
This query returns the total amount of money spent by each customer during all their shoppings. The
table returned looks like this:
cust_id SUM(total_price)
1 30
2 3
3 1
The way you have to understand the query is that we compute the sum of all amounts for each
customer. This is expressed by the GROUP BY cust_id. Now, if we would try to do this for each
product. This would correspond to the total money gained per product. The query looks like this:
item SUM(total_price)
apple 7
balloon 1
pillow 25
plastic bag 1
Update Query
The SQL UPDATE Query is used to modify the existing records in a table.
You can use WHERE clause with UPDATE query to update selected rows,
otherwise all the rows would be affected.
Syntax:
The basic syntax of UPDATE query with WHERE clause is as follows:
UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];
You can combine N number of conditions using AND or OR operators.
Example:
Consider the CUSTOMERS table having the following records:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Following is an example, which would update ADDRESS for a customer whose ID is 6:
SQL> UPDATE CUSTOMERS
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | Pune | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
If you want to modify all ADDRESS and SALARY column values in CUSTOMERS table,
you do not need to use WHERE clause and UPDATE query would be as follows:
SQL> UPDATE CUSTOMERS
SET ADDRESS = 'Pune', SALARY = 1000.00;
+----+----------+-----+---------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+---------+
| 1 | Ramesh | 32 | Pune | 1000.00 |
| 2 | Khilan | 25 | Pune | 1000.00 |
| 3 | kaushik | 23 | Pune | 1000.00 |
| 4 | Chaitali | 25 | Pune | 1000.00 |
| 5 | Hardik | 27 | Pune | 1000.00 |
| 6 | Komal | 22 | Pune | 1000.00 |
| 7 | Muffy | 24 | Pune | 1000.00 |
+----+----------+-----+---------+---------+
Delete Query in MySQL
The SQL DELETE Query is used to delete the existing records from a table.
You can use WHERE clause with DELETE query to delete selected rows, otherwise
all the records would be deleted.
Syntax:
The basic syntax of DELETE query with WHERE clause is as follows:
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
+----+----------+-----+-----------+----------+
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
If you want to DELETE all the records from CUSTOMERS table, you do not need to
use WHERE clause and
DELETE query would be as follows:
MySQL IN Clause
IN -> The IN operator is used to compare a value to a list of literal values that have
been specified.
SQL> SELECT * FROM CUSTOMERS WHERE AGE IN ( 25, 27 );
+----+----------+-----+---------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+---------+
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
+----+----------+-----+---------+---------+
1 ADDDATE()
2 DATE()
3 DATEDIFF()
4 DAY()
Synonym for DAYOFMONTH()
5 DAYOFMONTH()
7 DAYOFYEAR()
8 HOUR() e
9 MINUTE()
10 MONTH()
11 NOW()
12 SECOND()
13 TIME()
14 WEEKDAY()
15 YEAR()
16 DATE_FORMAT()
1 ABS()
7 CEILING()
Returns the smallest integer value that is not less than passed numeric expression
13 EXP()
Returns the base of the natural logarithm (e) raised to the power of passed numeric
expression.
14 FLOOR()
Returns the largest integer value that is not greater than passed numeric
expression.
21 MOD()
22 PI()
23 POW()
Returns the value of one expression raised to the power of another expression
26 RAND()
Returns a random floating-point value with in the range 0 to 1.0.
27 ROUND()
28 SIGN()
30 SQRT()
32 TRUNCATE()
Returns numeric exp1 truncated to exp2 decimal places. If exp2 is 0, then the result
will have no decimal point.
SQL JOIN
SQL Join is used to fetch data from two or more tables, which is joined to appear as single
set of data. It is used for combining column from two or more tables by using values
common to both tables.
JOIN Keyword is used in SQL queries for joining two or more tables. Minimum required
condition for joining table, is (n-1) where n, is number of tables. A table can also join to
itself, which is known as, Self Join.
Types of JOIN
Following are the types of JOIN that we can use in SQL:
Inner
Outer
Left
Right
Cross JOIN or Cartesian Product
This type of JOIN returns the cartesian product of rows from the tables in Join. It will return
a table which consists of records which combines each row from the first table with each
row of the second table.
Cross JOIN Syntax is,
SELECT column-name-list
FROM
table-name1 CROSS JOIN table-name2;
ID NAME
1 Abhi
2 Adam
4 Alex
ID Address
1 DELHI
2 MUMBAI
3 CHENNAI
ID NAME ID Address
1 Abhi 1 DELHI
2 Adam 1 DELHI
4 Alex 1 DELHI
1 Abhi 2 MUMBAI
2 Adam 2 MUMBAI
4 Alex 2 MUMBAI
1 Abhi 3 CHENNAI
2 Adam 3 CHENNAI
4 Alex 3 CHENNAI
As you can see, this join returns the cross product of all the records present in both the
tables.
ID NAME
1 Abhi
2 Adam
3 Alex
4 Anu
ID Address
1 DELHI
2 MUMBAI
3 CHENNAI
ID NAME ID Address
1 Abhi 1 DELHI
2 Adam 2 MUMBAI
3 Alex 3 CHENNAI
OUTER JOIN
Outer Join is based on both matched and unmatched data. Outer Joins subdivide further
into,
ID NAME
1 Abhi
2 Adam
3 Alex
4 Anu
5 Ashish
ID Address
1 DELHI
2 MUMBAI
3 CHENNAI
7 NOIDA
8 PANIPAT
ID NAME ID Address
1 Abhi 1 DELHI
2 Adam 2 MUMBAI
3 Alex 3 CHENNAI
ID NAME
1 Abhi
2 Adam
3 Alex
4 Anu
5 Ashish
and the class_info table,
ID Address
1 DELHI
2 MUMBAI
3 CHENNAI
7 NOIDA
8 PANIPAT
ID NAME ID Address
1 abhi 1 DELHI
2 adam 2 MUMBAI
3 alex 3 CHENNAI
ID NAME
1 Abhi
2 Adam
3 Alex
4 Anu
5 Ashish
ID Address
1 DELHI
2 MUMBAI
3 CHENNAI
7 NOIDA
8 PANIPAT
ID NAME ID Address
1 abhi 1 DELHI
2 adam 2 MUMBAI
3 alex 3 CHENNAI
A transaction in MySQL starts with the first executable SQL statement and ends when it
finds a commit or rolled back either explicitly or implicitly. It explicitly uses COMMIT or
ROLLBACK statement and implicitly when a DDL statement is used.
o First, it is required to check the availability of the requested amount in the first account.
o Next, if the amount is available, deduct it from the first account. Then, update the first
account.
o Finally, deposit the amount in the second account. Then update the second account to
complete the transaction.
o If any of the above processes fails, the transaction will be rolled back into its previous state.
Properties of Transaction
The transaction contains mainly four properties, which referred to as ACID property. Now,
we are going to discuss the ACID property in detail. The ACID property stands for:
1. Atomicity
2. Consistency
3. Isolation
4. Durability
Atomicity: This property ensures that all statements or operations within the transaction
unit must be executed successfully. Otherwise, if any operation is failed, the whole
transaction will be aborted, and it goes rolled back into their previous state. It includes
features:
o COMMIT statement.
o ROLLBACK statement.
o Auto-commit setting.
o Operational data from the INFORMATION_SCHEMA tables.
Consistency: This property ensures that the database changes state only when a
transaction will be committed successfully. It is also responsible for protecting data from
crashes. It includes features:
Isolation: This property guarantees that each operation in the transaction unit operated
independently. It also ensures that statements are transparent to each other. It includes
features:
Durability: This property guarantees that the result of committed transactions persists
permanently even if the system crashes or failed. It includes features:
o MySQL provides a START TRANSACTION statement to begin the transaction. It also offers
a "BEGIN" and "BEGIN WORK" as an alias of the START TRANSACTION.
o We will use a COMMIT statement to commit the current transaction. It allows the database
to make changes permanently.
o We will use a ROLLBACK statement to roll back the current transaction. It allows the
database to cancel all changes and goes into their previous state.
o We will use a SET auto-commit statement to disable/enable the auto-commit mode for
the current transaction. By default, the COMMIT statement executed automatically. So if
we do not want to commit changes automatically, use the below statement:
1. SET autocommit = 0;
2. OR,
3. SET autocommit = OFF:
1. SET autocommit = 1;
2. OR,
3. SET autocommit = ON:
MySQL Transaction Example
Suppose we have two tables named "employees" and "Orders" that contains the
following data:
Table: employees
Table: orders
COMMIT Example
If we want to use a transaction, it is required to break the sql statements into logical
portions. After that, we can define whether the data should be committed or rollback.
ROLLBACK Example
We can understand the rollback transaction with the help of the following illustration.
First, open the MySQL command prompt and log into the database server using the
password. Next, we have to select a database.
Suppose our database contains the "Orders" table. Now, the following are the scripts that
perform the rollback operations:
After the execution of the above statement, we will get the output as below that shows
all the records from the table Orders were successfully deleted.
Now, we need to open a separate session of MySQL database server and execute the
below statement to verify the data in Orders table:
1. SELECT * FROM Orders;
Although we have made changes in the first session, we still can see the records are
available in the table. It is because the changes are not permanent until we have not
executed the COMMIT or ROLLBACK statement in the first session.
Therefore if we want to make changes permanent, use the COMMIT statement. Otherwise,
execute the ROLLBACK statement to roll back the changes in the first session.
1. -- 3. Rollback changes
2. ROLLBACK;
3. -- 4. Verify the records in the first session
4. SELECT * FROM Orders;
After the successful execution, it will produce the following result where we can see that
the change has been rolled back.
Statements that cannot be a rollback in using MySQL Transaction.
MySQL Transaction cannot be able to roll back all statements. For example, these
statements include DDL (Data Definition Language) commands such as CREATE, ALTER,
or DROP database as well as CREATE, UPDATE, or DROP tables or stored routines. We
have to make sure that when we design our transaction, these statements do not include.
MySQL - INDEXES
A database index is a data structure that improves the speed of operations in a table.
Indexes can be created using one or more columns, providing the basis for both rapid
random lookups and efficient ordering of access to records.
While creating index, it should be taken into consideration which all columns will be used
to make SQL queries and create one or more indexes on those columns.
Practically, indexes are also a type of tables, which keep primary key or index field and
a pointer to each record into the actual table.
The users cannot see the indexes, they are just used to speed up queries and will be
used by the Database Search Engine to locate records very fast.
The INSERT and UPDATE statements take more time on tables having indexes,
whereas the SELECT statements become fast on those tables. The reason is that while
doing insert or update, a database needs to insert or update the index values as well.