0% found this document useful (0 votes)
89 views

Lecture3 PHP MySQL

The document discusses MySQL relations and design, PHP, and MySQL. It provides an overview of databases, introduces SQL, discusses table relationships and joins, and covers using MySQL with PHP. The document contains sections on database introduction, SQL, table relationships, joins, and transactions.

Uploaded by

Huda Ghazi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
89 views

Lecture3 PHP MySQL

The document discusses MySQL relations and design, PHP, and MySQL. It provides an overview of databases, introduces SQL, discusses table relationships and joins, and covers using MySQL with PHP. The document contains sections on database introduction, SQL, table relationships, joins, and transactions.

Uploaded by

Huda Ghazi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 119

MySQL Relations and Design, PHP & MySQL

Table Relationships and Joins, Transactions

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

HTTP Server File TCP/Socket

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

Order# Date Customer Product S/N Unit Price Qty Total


00315 07/16/ David Rivers Oil Pump OP147-0623 69.90 1 69.90
2016

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

Clients Engine Database

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

§ Download HeidiSQL, DataGrip, MySQL Workbench or something


else

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

§ Each row is called a record or entity


§ Columns (fields) define the type of data they contain

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

SELECT * FROM projects WHERE start_date = '1/1/2006'

INSERT INTO projects(name, start_date)


VALUES('Introduction to MySQL', '1/1/2006')

UPDATE projects
SET end_date = '8/31/2006'
WHERE start_date = '1/1/2006'

DELETE FROM projects


WHERE start_date = '1/1/2006'
36
SQL Queries
§ We can communicate with the database engine using SQL
§ Queries provide greater control and flexibility
§ To create a database using SQL

CREATE DATABASE people Database name

§ SQL keywords are traditionally capitalized

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

List of columns Table name


(* for everything)

department_id name manager_id


1 Engineering 12
2 Tool design 4
3 Sales 273
… … …

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
… … …

§ You can shorten fields or clarify abbreviations


SELECT c.duration,
c.ACG AS 'Access Control Gateway'
FROM Calls AS c
41
Concatenation Operator
§ You can concatenate column names or strings using CONCAT
§ String literals are enclosed in single or double quotes
§ Table and column names containing special symbols use '' or ''
SELECT CONCAT(first_name, ' ', last_name) AS `Full Name`,
employee_id AS `No.`
FROM employees

Full Name No.


Guy Gilbert 1
Kevin Brown 2
… …
42
Problem: Employee Summary
§ Find information about all employees, listing their full name,
job title and salary
§ Use concatenation to display first and last names as one field

§ Create and Query SoftUni database


43
Solution: Employee Summary
Concatenation

SELECT CONCAT(first_name, ' ', last_name)


AS `Full Name`,
job_title, Column alias
salary
FROM employees

44
Filtering the Selected Rows
§ Use DISTINCT to eliminate duplicate results
SELECT DISTINCT department_id
FROM employees

§ You can filter rows by specific conditions using the


WHERE clause
SELECT last_name, department_id
FROM employees
WHERE department_id = 1

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)

§ Using BETWEEN operator to specify a range


SELECT last_name, salary FROM employees
WHERE salary BETWEEN 20000 AND 22000

§ Using IN / NOT IN to specify a set of values


SELECT first_name, last_name, manager_id FROM employees
WHERE manager_id IN (109, 3, 16)
46
Comparing with NULL
§ NULL is a special value that means missing value
§ Not the same as 0 or a blank space
§ Checking for NULL values
SELECT last_name, manager_id FROM employees
This is always false!
WHERE manager_id = NULL

SELECT last_name, manager_id FROM employees


WHERE manager_id IS NULL

SELECT last_name, manager_id FROM employees


WHERE manager_id IS NOT NULL
47
Sorting with ORDER BY
§ Sort rows with the ORDER BY clause
§ ASC - ascending order, default last_name hire_date
§ DESC - descending order Gilbert 1998-07-31
Brown 1999-02-26
SELECT last_name, hire_date Tamburello 1999-12-12
FROM employees … …
ORDER BY hire_date
last_name hire_date
SELECT last_name, hire_date Valdez 2005-07-01
FROM employees Tsoflias 2005-07-01
ORDER BY hire_date DESC Abbas 2005-04-15
… …
48
Inserting Data
§ Insert a new Employee (id will be auto-generated)
INSERT INTO employees(email, first_name, last_name)
VALUES ('[email protected]', 'Radina', 'Georgieva')

§ Insert a few new Employees


INSERT INTO employees(email, first_name, last_name)
VALUES
('[email protected]', 'Elena', 'Petrova'),
('[email protected]', 'Mirela', 'Mihailova'),
('[email protected]', 'Hristo', 'Dimitrov')
49
Updating Data
§ The SQL UPDATE command
New values
UPDATE employees
SET last_name = 'Brown'
WHERE id = 1

UPDATE employees
SET salary = salary * 1.10,
job_title = CONCAT('Senior ', JobTitle)
WHERE id = 3

§ Note: Don't forget the WHERE clause!

50
Updating Data (2)
§ Update existing post - change title
UPDATE posts
SET title = 'Title Updated!'
WHERE id = 2;

§ Update existing post - change date


UPDATE posts
SET date = STR_TO_DATE('31-12-2018', '%d-%m-%Y')
WHERE YEAR(date) = 2018;

51
Problem: Update Projects
§ Mark all unfinished Projects as being completed today
§ Unfinished projects have their end_date set to NULL

name end_date name end_date


Classic Vest NULL Classic Vest 2017-01-23
HL Touring Frame NULL HL Touring Frame 2017-01-23
LL Touring Frame NULL LL Touring Frame 2017-01-23
… … … …

§ Note: Create and Query SoftUni database

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;

§ Don't forget the WHERE clause!


§ Delete all Employees where First Name is Hristo
DELETE FROM employees
WHERE first_name = 'Hristo';

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

§ To drop a table - delete data and structure


DROP TABLE employees Table name

§ To drop entire database


DROP DATABASE people Database 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

employee department_name salary


Adam Database Support 5,000
department_name total_salary
John Database Support 15,000
Database Support 20,000
Jane Application Support 10,000
Application Support 30,000
George Application Support 15,000
Software Support 15,000
Lila Application Support 5,000
Fred Software Support 15,000

60
SUM Syntax
§ If any department has no salaries NULL will be displayed

Grouping Column New Column Alias

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

employee department_name salary


Adam Database Support 5,000
department_name max_salary
John Database Support 15,000
Database Support 20,000
Jane Application Support 10,000
Application Support 30,000
George Application Support 15,000
Software Support 15,000
Lila Application Support 5,000
Fred Software Support 15,000

62
MAX Syntax

Grouping Column New Column Alias

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

employee department_name salary


Adam Database Support 5,000
department_name min_salary
John Database Support 15,000
Database Support 5,000
Jane Application Support 10,000
Application Support 5,000
George Application Support 15,000
Software Support 15,000
Lila Application Support 5,000
Fred Software Support 15,000

64
MIN Syntax

Grouping Column New Column Alias

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

employee department_name salary


Adam Database Support 5,000
department_name average_salary
John Database Support 15,000
Database Support 10,000
Jane Application Support 10,000
Application Support 10,000
George Application Support 15,000
Software Support 15,000
Lila Application Support 5,000
Fred Software Support 15,000

66
AVG Syntax

Grouping Column New Column Alias

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?

first last registered email email2


David Rivers 05/02/2016 [email protected] [email protected]
Sarah Thorne 07/17/2016 [email protected] NULL
Empty records
Michael Walters 11/23/2015 [email protected] NULL

order_id date customer product s/n price


00315 07/16/2016 David Rivers Oil Pump OP147-0623 69.90
00315 07/16/2016 David Rivers Accessory Belt AB544-1648 149.99
00316 07/17/2016 Sarah Thorne Wiper Fluid WF000-0001 99.90
00317 07/18/2016 Michael Walters Oil Pump OP147-0623 69.90

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]

§ The connection is established via a Foreign Key in one table


pointing to the Primary Key in another
70
Relationships
§ There are 3 types of relationships in relational
database design
§ One-to-One
§ One-to-Many / Many-to-One
§ Many-to-Many

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

Primary key Primary key Foreign key


Mountains Peaks
id name id mountain_id
1 Causasus 61 1
66 1

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)

CREATE TABLE employees (


id INT PRIMARY KEY,
Table
name VARCHAR(50)
Employees
);

CREATE TABLE projects (


id INT PRIMARY KEY,
name VARCHAR(50) Table Projects
);

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

Primary key Foreign key Primary key


cars drivers
id driver_id id name
1 166 166 …
2 102 102 …

Relation
79
Setup

CREATE TABLE drivers(


id INT PRIMARY KEY,
name VARCHAR(50)
);
One driver
CREATE TABLE cars( per car
id INT PRIMARY KEY,
driver_id INT UNIQUE,
CONSTRAINT fk_cars_drivers
FOREIGN KEY (driver_id) REFERENCES drivers(id)
);
80
Foreign Key

Constraint Name

CONSTRAINT fk_cars_drivers
FOREIGN KEY (driver_id) Foreign Key
REFERENCES drivers(id)

Referent Table Primary Key

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

employee_name department_id department_name


Edward 3 Sales

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

SELECT * FROM employees AS e Table Depatments

INNER JOIN departments AS d


ON e.id = d.id;
Inner Join Join Conditions

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

SELECT * FROM employees AS e Table Depatments


LEFT OUTER JOIN departments AS d
Left Join ON e.id = d.id;

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

Cross Table Selection

SELECT e.first_name, e.last_name,


t.name as town, a.text Table Employees
FROM employees AS e
JOIN addresses AS a ON e.id = a.id
JOIN towns AS t ON a.id = t.id
ORDER BY e.first_name, e.last_name
Table Towns
LIMIT 5;

91
Problem: Sales Employees
§ Find all employees that are in the "Sales" department. Use
"SoftUni" database
§ Follow the specified format

§ Order them by employee_id DESC

92
Solution: Sales Employees

Cross Table Selection

SELECT e.id, e.first_name, e.last_name,


d.name AS name
FROM employees AS e Table Departments
INNER JOIN departments AS d
ON e.id = d.id
WHERE d.name = 'Sales'
ORDER BY e.id DESC; WHERE Predicate

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

Using MySQL and PHP


Using MySQL in PHP: Connect
§ Use mysqli class to connect to MySQL from PHP script
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'blog';
$mysqli = new mysqli($host, $user, $pass, $db);
$mysqli->set_charset("utf8");
if ($mysqli->connect_errno)
die('Cannot connect to MySQL');

§ 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');

§ Execute a SQL query through existing MySQL connection


$result = $mysqli->query('SELECT * FROM posts');
if (!$result)
die('Cannot read `posts` table');
98
Using MySQL in PHP: Fetch Records
§ Process the returned result set (table rows / records)
$result =
$mysqli->query('SELECT * FROM posts');
while ($row = $result->fetch_assoc()) {
$title = $row['title'];
// TODO: print the title
$content = $row['content'];
// TODO: print the content
}

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/>";
}

§ Note: always put the connection code in a separate file. 10


2
Connect and Process Query
§ We will use the PDO extension
try {
$db = new PDO('mysql:host=localhost;dbname=test',$user,$pass);
$result = $db->query('SELECT * FROM Users', PDO::FETCH_ASSOC);
foreach ($result as $row) {
print_r($row);
}
Close the
$result = null;
connection
$db = null;
} 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
]);

} catch (PDOException $e) {


print "Error!: " . $e->getMessage() . "<br/>";
}

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()

Include and require


Including a Script from Another Script
Include and Require
§ include and require load and evaluate a file holding PHP code
main.php header.php footer.php
require "conn.php"; echo…. echo….
require "header.php";
echo "page body"; conn.php
include "footer.php"; $db = new PDO(…);

§ Difference between include and require


§ If file is not found include produces a warning
§ require produces a fatal error
11
3
include_once and iequire_once

§ 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()…

§ But With include_once and require_once, if file is already


included, nothing happens, and the duplication will be skipped.
114
Summary
§ …
§
§ …RDBMS store and manage data
§ MySQL server also stores data types
§ …
§ Modeling database
§ Using tools like HeidiSQL
§ Execute basic SQL Queries

11
5
Summary (2)

… relations reduce repetition and


§ §Table
complexity
§ …
§ A SQL join is a SQL instruction to combine
… from two sets of data (i.e. two tables)
§data
§ Using PHP we can
§ Connect and manage connection
§ Execute SQL Queries
§ With Transactions we satisfy the ACID
properties
11
6
© SoftUni – https://about.softuni.bg. Copyrighted document. Unauthorized copy, reproduction or use is not permitted.
Trainings @ Software University (SoftUni)
§ Software University – High-Quality Education,
Profession and Job for Software Developers
§ softuni.bg, about.softuni.bg
§ Software University Foundation
§ softuni.foundation
§ Software University @ Facebook
§ facebook.com/SoftwareUniversity
§ Software University Forums
§ forum.softuni.bg 11
8
License

§ This course (slides, examples, demos, exercises, homework,


documents, videos and other assets) is copyrighted content
§ Unauthorized copy, reproduction or use is illegal
§ © SoftUni – https://about.softuni.bg/
§ © Software University – https://softuni.bg

11
9

You might also like