Lecture3 PHP MySQL
Lecture3 PHP MySQL
SoftUni Team
Technical Trainers
Software University
https://softuni.bg
Table of Contents
1. Databases
§ Big Picture
§ Data Management
§ Database Engine & Storage
§ Data Types, Database Modeling
2. Introduction to SQL
§ SELECT, INSERT, UPDATE, DELETE
2
Table of Contents
3. Aggregate Functions
4. Table Relationships
5. Joins
6. Using MySQL and PHP
7. Transactions
3
Database
Introduction
4
Big Picture
Internet Web
Browser PHP DB
Server
DB Client
5
Storage vs. Management
SALES RECEIPT
Date 07/16/2016
Order# [00315]
Customer David Rivers 00315 - 07/16/2016
David Rivers
Product Oil Pump
Oil Pump (OP147-0623)
S/N OP147-0623 1 x 69.90
Unit Price 69.90
Quantity 1
Total 69.90
6
Storage vs Management
7
Storage vs. Management (2)
§ Storing data is not the primary reason to use a database
§ Flat storage eventually runs into issues with
§ Size
§ Ease of updating
§ Accuracy
§ Security
§ Redundancy
§ Importance
8
Database Engine
11
Database Engine Flow
§ SQL Server uses the Client-Server Model
Query Access
Data Data
10
Database Engine Flow (2)
11
Top Database Engines
Source: http://db-engines.com/en/ranking 12
Database Types
§ Relational database (RDBMS)
§ Document-oriented database
§ Key-value database
§ TimeSeries
§ Triplestore
§ And many more…
K -> V
13
Databases and RDBMS
§ A database is an organized collection of information
§ It imposes rules on the contained data
§ A Relational Data Base Management System provides tools
to manage the database
§ It parses requests from the user and takes the appropriate
action
§ The user doesn’t have direct access to the stored data
14
MySQL / MariaDB
17
Download Clients & Servers
§ Download XAMPP or Official MySQL Server or MariaDB Server
16
MySQL Server Architecture
§ Logical Storage Instance
§ Instance Database Database
§ Database/Schema Table Table Table
§ Table
View View
Database
§ Physical Storage Procedure
§ Data files and Log files
§ Data pages
Data Logs
17
Database Table Elements
§ The table is the main building block of any databasе
Column
customer_id first_name birthdate city_id
1 Brigitte 03/12/1975 101
2 August 27/05/1968 102 Cell
3 Benjamin 15/10/1988 103 Row
4 Denis 07/01/1993 104
18
in te ge r
cha
te x t r
float
Data Types in MySQL Server
21
Basic Data Types in MySQL
§ Numeric
§ integer - different sizes
§ Representing real numbers
§ float
§ double
§ decimal
20
Basic Data Types in MySQL (2)
§ Strings
§ char(size) - fixed size string
§ varchar(size) - variable size string
§ Text data block
§ text
§ tinytext
§ mediumtext
§ longtext
21
Basic Data Types in MySQL (3)
§ Binary data
§ binary(size) - fixed binary byte strings
§ varbinary(size) - variable size binary byte strings
§ Date and time
§ date - range is '1000-01-01 to 9999-12-31'
§ datetime - range is '1000-01-01 00:00:00' to '9999-12-31
23:59:59'
§ timestamp - range of '1970-01-01 00:00:01' UTC to '2038-01-19
03:14:07' UTC
22
Structured Query Language
§ To communicate with the Engine we use SQL
§ Declarative language
§ Logically divided in four sections
§ Data Definition - describe the structure of our data
§ Data Manipulation - store and retrieve data
§ Data Control - define who can access the data
§ Transaction Control - bundle operations and allow rollback
23
Database Modeling
Data Definition Using HeidiSQL
25
Working with HeidiSQL
§ HeidiSQL is a tool that helps us when working with the database
and its objects and enable us
§ To create a new database
§ To create objects in the database (tables, stored procedures,
relationships and others)
§ To change the properties of objects
§ To enter records into the tables
25
Make New Connection
§ Connect to MySQL Server with user root and the password you
set up
26
Creating a New Database
§ Select Create new -> Database from the context menu
Encoding
27
Creating Tables
§ From the context menu under Create new -> Table inside the
desired database
28
Creating Tables (2)
§ To add a field use Add column
29
Creating Tables (3)
§ A Primary Key is used to uniquely identify and index records
§ Click PRIMARY from the context menu of the desired field
30
Field Defaults
§ You can set a default value for every field
§ No default value makes the field mandatory on row insert
31
Manipulate Data
§ For all kinds of data manipulations select the Data tab
32
Altering Tables
§ You can change the properties of a table after its creation
33
SQL
SQL
Introduction
34
What is SQL?
§ Structured Query Language (SQL)
§ Declarative language for working with relational data
§ Meant to be as close to regular English as possible
§ Supports definition, manipulation and access control of records
§ MySQL Dialect
§ Supports own control statements (if statements, loops etc..)
§ Designed for writing logic inside the database
35
SQL - Few Examples
SELECT first_name, last_name, job_title FROM employees
UPDATE projects
SET end_date = '8/31/2006'
WHERE start_date = '1/1/2006'
37
Table Creation in SQL
Table name
CREATE TABLE employees
(
Custom properties
id int NOT NULL,
email varchar(50) NOT NULL,
first_name varchar(50),
last_name varchar(50)
)
Column name Data type
38
Retrieve Records in SQL
§ Selecting all columns from the " departments" table
SELECT * FROM departments
39
Retrieve Records in SQL
§ Selecting specific columns
SELECT department_id, name
FROM departments
department_id name
1 Engineering
2 Tool design
3 Sales
… …
40
Column Aliases
§ Aliases rename a table or a column heading
SELECT employee_id AS id, first_name, last_name
FROM employees
id first_name last_name
1 Guy Gilbert
2 Kevin Brown
… … …
44
Filtering the Selected Rows
§ Use DISTINCT to eliminate duplicate results
SELECT DISTINCT department_id
FROM employees
45
Other Comparison Conditions
§ Conditions ca be combined using NOT, OR, AND and brackets
SELECT last_name FROM employees
WHERE NOT (manager_id = 3 OR manager_id = 4)
UPDATE employees
SET salary = salary * 1.10,
job_title = CONCAT('Senior ', JobTitle)
WHERE id = 3
50
Updating Data (2)
§ Update existing post - change title
UPDATE posts
SET title = 'Title Updated!'
WHERE id = 2;
51
Problem: Update Projects
§ Mark all unfinished Projects as being completed today
§ Unfinished projects have their end_date set to NULL
52
Solution: Update Projects
UPDATE projects
SET end_date = '2017-01-23'
WHERE end_date IS NULL
Filter only records
with no value
53
Deleting Data
§ Deleting specific rows from a table
DELETE FROM employees
WHERE id = 6;
54
Deleting from Database
§ Deleting structures
§ You can drop keys, constraints, tables and entire databases
§ Deleting all data in a table
§ Both actions cannot be undone - use with caution!
55
Dropping, Deleting and Truncating
§ To delete all the entries in a table
DELETE FROM employees TRUNCATE TABLE employees Table name
56
Аaggregate Functions
COUNT, SUM, MAX, MIN, AVG…
COUNT
§ COUNT - counts the values (not nulls) in one or more columns
based on grouping criteria
employee department_name salary
Adam Database Support 5,000 department_name SalaryCount
John Database Support 15,000 Database Support 2
Jane Application Support 10,000 Application Support 3
George Application Support 15,000 Software Support 1
Lila Application Support 5,000
Fred Software Support 15,000
58
COUNT Syntax
§ Note that we when we use COUNT, we will ignore any
employee with NULL salary
Grouping Column New Column Alias
SELECT e.`department_id`,
COUNT(e.`salary`) AS 'Salary Count'
FROM `employees` AS e
GROUP BY e.`department_id`;
Grouping Columns
59
SUM
§ SUM - sums the values in a column
60
SUM Syntax
§ If any department has no salaries NULL will be displayed
SELECT e.`department_id`,
SUM(e.`salary`) AS 'TotalSalary'
FROM `employees` AS e
Table Alias
GROUP BY e.`department_id`;
Grouping Columns
61
MAX
§ MAX - takes the maximum value in a column
62
MAX Syntax
SELECT e.`department_id`,
MAX(e.`salary`) AS 'MaxSalary'
FROM `employees` AS e Table Alias
GROUP BY e.`department_id`;
Grouping Columns
63
MIN
§ MIN takes the minimum value in a column
64
MIN Syntax
SELECT e.`department_id`,
MIN(e.`salary`) AS 'MinSalary'
FROM `employees` AS e Table Alias
GROUP BY e.`department_id`;
Grouping Columns
65
AVG
§ AVG calculates the average value in a column
66
AVG Syntax
SELECT e.`department_id`,
AVG(e.`salary`) AS 'AvgSalary'
FROM `employees` AS e Table Alias
GROUP BY e.`department_id`;
Grouping Columns
67
Table Relationships
Why Split Related Data?
69
Related Tables
§ Split the data and introduce relationships between the tables to
avoid repeating information
id first last registered user_id email
203 David Rivers 05/02/2016 203 [email protected]
204 Sarah Thorne 07/17/2016 204 [email protected]
205 Michael Walters 11/23/2015 205 [email protected]
Primary Key Foreign Key 203 [email protected]
71
Relationships (2)
§ Relationships between tables are based on
interconnections: PRIMARY KEY / FOREIGN KEY
Primary key Foreign key
Primary key
towns
countries
id name country_id
1 Sofia 1 id name
2 Varna 1 1 Bulgaria
3 Munich 2 2 Germany
4 Berlin 2 3 Russia
5 Moscow 3
Relationships 72
One-to-Many/Many-to-One
Relation
73
Setup
CREATE TABLE mountains( Primary key
id INT PRIMARY KEY,
name VARCHAR(50)
);
CREATE TABLE peaks ( Table Peaks
id INT PRIMARY KEY,
mountain_id INT,
CONSTRAINT fk_peaks_mountains
FOREIGN KEY (mountain_id) Foreign Key
REFERENCES mountains(id)
);
74
Foreign Key
Constraint Name
CONSTRAINT fk_peaks_mountains
FOREIGN KEY (mountain_id) Foreign Key
REFERENCES mountains(id);
Referent Table Primary Key
75
Many-to-Many
Primary key Primary key
employees projects
id name id name
1 … 4 …
40 … 24 …
Mapping table
employees_projects
employee_id project_id
1 4
40 24
76
Setup(1)
77
Setup(2)
CREATE TABLE employees_projects(
employee_id INT,
Mapping Table
project_id INT,
CONSTRAINT pk_employees_projects
PRIMARY KEY(employee_id, project_id),
CONSTRAINT fk_employees_projects_employees
FOREIGN KEY(employee_id)
REFERENCES employees(id),
CONSTRAINT fk_employees_projects_projects
FOREIGN KEY(project_id)
REFERENCES projects(id)
);
78
One-to-One
Relation
79
Setup
Constraint Name
CONSTRAINT fk_cars_drivers
FOREIGN KEY (driver_id) Foreign Key
REFERENCES drivers(id)
81
Joins
Gathering Data from Multiple Tables
Data from Multiple Tables
§ Sometimes you need data from several tables
Employees Departments
name department_id id name
Edward 3 3 Sales
John NULL 4 Marketing
5 Purchasing
83
Types of Joins
§ At the top level there are mainly 3 types of joins
§ INNER
§ OUTER
§ CROSS
84
Types of Joins (2)
§ INNER JOIN - fetches data if present in both the tables
§ OUTER JOIN are of 3 types
§ LEFT OUTER JOIN
§ RIGHT OUTER JOIN
§ FULL OUTER JOIN
§ CROSS JOIN, as the name suggests, does [n X m] that joins
everything to everything
85
Inner Join
Employees Departments
id department_id id name
263 3 3 Sales
270 NULL 4 Marketing
5 Purchasing
Result
employee_id department_id department_id department_name
263 3 3 Sales
86
Inner Join Syntax
Table Employees
87
Left Outer Join
Employees Departments
id department_id id name
263 3 3 Sales
270 NULL X 4 Marketing
5 Purchasing
Result
employee_id department_id department_id department_name
263 3 3 Sales
270 NULL NULL NULL
88
Left Outer Join Syntax
Table Employees
Join Conditions
89
Problem: Addresses with Towns
§ Display address information of all employees in "SoftUni"
database. Select first 5 employees
§ The exact format of data is shown below
§ Order them by first_name, then by last_name (ascending)
90
Solution: Addresses with Towns
91
Problem: Sales Employees
§ Find all employees that are in the "Sales" department. Use
"SoftUni" database
§ Follow the specified format
92
Solution: Sales Employees
93
Problem: Countries Without Any Mountains
§ Display the count of all countries which don't have a mountain
§ Use Geography Database
country_count
231
94
Solution: Countries Without Any Mountains
SELECT
COUNT(*) AS country_count
FROM
countries AS c
LEFT JOIN mountains_countries AS mc
ON c.code = mc.code
WHERE mc.id IS NULL;
95
MySQL
PHP
§ Note: die is similar to echo & print but exits the execution.
97
Using MySQL in PHP: Connect & Query
§ Use mysqli class to connect to MySQL from PHP script
$mysqli = new mysqli('localhost', 'root', '', 'blog');
$mysqli->set_charset("utf8");
if ($mysqli->connect_errno) die('Cannot connect to MySQL');
99
Using MySQL in PHP: Prepared Statement
§ Using a prepared statement with parameters
function deletePost($mysqli, $id) {
$statement = $mysqli->prepare(
"DELETE FROM posts WHERE id = ?");
s - string
$statement->bind_param("i", $id); i - integer
$statement->execute(); d - double
return $statement->affected_rows > 0;
}
10
0
PDO
Using PDO
Connecting to Database Server
§ We will use the PDO extension
$host = "localhost"; // define("host", "localhost");
$dbn = "erp_system"; // define("dbn", "erp_system");
$user = "root"; // define("user", "root");
$pass = "pasword"; // define("pass", "password");
$db = null;
try {
$db = new PDO("mysql:host=$host;dbname=$dbn",$user,$pass, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
}
10
3
Using Prepared Statement (SELECT)
try {
$db = new PDO('mysql:host=localhost;dbname=test',$user,$pass);
$stmt = $db->prepare("SELECT * FROM Users WHERE fname = ?");
if ($stmt->execute([ $_GET['fname’] ])) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
print_r($row);
}
} Close the
$stmt = null; connection
$db = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
}
10
4
Using Prepared Statement (INSERT)
try {
$stmt = $db->prepare("INSERT INTO Users (fname, lname) VALUES
(?, ?)");
$stmt->bindParam(1, $fname); We can bind variables
$stmt->bindParam(2, $lname); to parameters
$fname = 'Joro';
$lname = 'Petrov';
$stmt->execute();
$fname = 'Vasil';
Never forget to close
$lname = 'Georgiev'; the connection
$stmt->execute();
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
} 10
5
Using Prepared Statement (INSERT)
try {
$stmt = $db->prepare(
"INSERT INTO Users (fname, lname)
VALUES (:fname, :lname)");
$stmt->execute([ We can bind variables
"fname" => "Azad" to parameters with
"lname" => "Kamaran" named parameters
]);
10
6
ATOMICITY
CONSISTENCY
ISOLATION
DURABILITY
Transactions
Following the ACID Properties
Running Transactions
§ A transaction is a sequence of operations performed
as a single logical unit of work
Mark start of
transaction
START TRANSACTION
INSERT INTO Projects(Name, StartDate)
VALUES('Introduction to MySQL', '1/1/2006')
COMMIT or ROLLBACK
Confirm or cancel
the changes
10
8
ACID
§ Atomicity
§ Atomicity requires that each transaction be "all or
nothing"
§ Consistency
§ The consistency property ensures that any transaction
will bring the database from one valid state to another
10
9
ACID (2)
§ Isolation
§ The isolation property ensures that the concurrent
execution of transactions results
§ Durability
§ The durability property ensures that once a transaction
has been committed
11
0
Transactions with PHP
try { Init connection
$db->beginTransaction();
$stmt = $db->prepare("INSERT INTO Users (fname, lname) VALUES
(?, ?)");
$stmt->bindParam(1, $fname);
$stmt->bindParam(2, $lname);
$fname = 'Joro';
Never forget to close
$lname = 'Petrov';
the connection
$stmt->execute();
$db->commit();
} catch (PDOException $e) {
$db->rollBack();
print "Error!: " . $e->getMessage() . "<br/>";
}
11
1
include()
require()
§ With include and require you can include one file many
times and each time it is evaluated
main.php header.php footer.php
require "header.php"; function test(); function test();
echo "Page body";
include "header.php";
Fatal error: Cannot redeclare test()…
11
5
Summary (2)
11
9