M 02 S 02 MySQL Databases Day 2
M 02 S 02 MySQL Databases Day 2
MySQL in PHP
v3.0
1
Agenda
2
Changing and
deleting data in
tables
3
Changing the data values
Replace data from a table using the UPDATE UPDATE is usually used with WHERE clause
query: (otherwise all data from the table will be changed).
UPDATE table_name
SET
col_name_1 = value1,
col_name_2 = value2,
...
WHERE col_name_3 = some_value;
4
Changing the data values
PHP
UPDATE users $sql = "UPDATE users
SET user_name="Gregory" SET user_name='Gregory'
WHERE user_id=2; WHERE user_id=2";
SELECT * FROM users; try {
+---------+-----------+ $result = $conn->query($sql);
| user_id | user_name | echo "The entry was updated.";
+---------+-----------+ } catch (PDOException $e) {
| 1 | William | echo "Error; . $e->getMessage();
| 2 | Gregory | }
| ... |
+---------+-----------+
4 rows in set (0.00 sec)
5
Changing the data values - prepared statement
PHP PHP - data from a form
$sql = "UPDATE users $userName = $_POST['userName'];
SET user_name='Gregory' $userId = $_POST['userId'];
WHERE user_id=2"; $sql = "UPDATE users
SET user_name=:userName
try { WHERE user_id=:userId";
$result = $conn->query($sql); try {
echo "The entry was updated."; $stmt = $conn->prepare($sql);
} catch (PDOException $e) { $stmt->execute([
echo "Error: " . $e->getMessage(); 'userName' => $userName,
} 'userId' => $userId
]);
echo "The entry was updated.";
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
6
Deleting data from table
We delete data from a table using the DELETE DELETE is usually used with WHERE clause
query: (otherwise all data from the table will be changed).
DELETE FROM table_name
WHERE some_column = some_value;
7
Deleting data from table
8
Deleting data from table - prepared statement
9
Exercises
Exercise time
Day 2
Changing and deleting data
10
Table
modification
11
Table modification
The appearance of the table (number of columns, data stored in them) can be changed using the ALTER
TABLE command:
#Adding a new column:
ALTER TABLE table_name ADD column_name datatype;
#Removing the table:
ALTER TABLE table_name DROP COLUMN column_name;
#Changing the type of data kept in the column:
ALTER TABLE table_name MODIFY COLUMN column_name new_datatype;
12
Table modification
+---------+------------+-----+-----+---------+----------------+
|Field |Type | Null| Key | Default | Extra |
+---------+------------+-----+-----+---------+----------------+
|user_id |int(11) | NO | PRI | NULL | auto_increment |
|user_name|varchar(255)| YES | | NULL | |
+---------+------------+-----+-----+---------+----------------+
2 rows in set (0.00 sec)
13
Table modification
14
Deleting table
The table can be removed from our database by We can destroy the entire database using the
using the DROP TABLE query: DROP DATABASE query ;
DROP TABLE table_name; DROP DATABASE db_name;
15
Exercises
Exercise time
Day 2
Table modification
16
Joining tables
17
Joining tables
SELECT column_name(s)
The results of two (or more) tables at once can be
FROM table1
obtained by using the construction JOIN ... ON ...
JOIN table2
These are the four possibilities to join tables: ON table1.col_name=table2.col_name;
INNER,
LEFT,
RIGHT,
FULL.
18
Joining tables
CREATE TABLE customers(
customer_id int NOT NULL AUTO_INCREMENT,
name varchar(255) NOT NULL,
PRIMARY KEY(customer_id)
);
CREATE TABLE addresses(
address_id int NOT NULL AUTO_INCREMENT,
customer_id int,
street varchar(255),
PRIMARY KEY(address_id)
);
19
INNER JOIN
20
INNER JOIN
+-------------+-------+ +----------+-----------+---------------+
| customer_id | name | |address_id|customer_id|street |
+-------------+-------+ +----------+-----------+---------------+
| 1 | Jack | | 1| 1|Jack's address |
| 3 | Paul | | 2| 3|Paul's address |
| 4 | Jacob | | 3| 10|Wrong address |
+-------------+-------+ +----------+-----------+---------------+
21
INNER JOIN
SELECT * FROM customers
JOIN addresses
ON customers.customer_id = addresses.customer_id;
+-------------+-------+------------+-------------+---------------+
| customer_id | name | address_id | customer_id |street |
+-------------+-------+------------+-------------+---------------+
| 1 | Jack | 1 | 1 |Jack's address |
| 3 | Paul | 2 | 3 |Paul's address |
+-------------+-------+------------+-------------+---------------+
22
INNER JOIN
SELECT * FROM customers
JOIN addresses
ON customers.customer_id = addresses.customer_id;
+-------------+-------+------------+-------------+---------------+
| customer_id | name | address_id | customer_id |street |
+-------------+-------+------------+-------------+---------------+
| 1 | Jack | 1 | 1 |Jack's address |
| 3 | Paul | 2 | 3 |Paul's address |
+-------------+-------+------------+-------------+---------------+
Returned records are those for which both tables have a common (of the same value) customer_id
column.
23
LEFT JOIN
24
LEFT JOIN
+-------------+-------+------------+-------------+----------------+
| customer_id | name | address_id | customer_id |street |
+-------------+-------+------------+-------------+----------------+
| 1 | Jack | 1 | 1 |Jack's address |
| 3 | Paul | 2 | 3 |Paul's address |
| 4 | Jacob | NULL | NULL |NULL |
+-------------+-------+------------+-------------+----------------+
25
LEFT JOIN
+-------------+-------+------------+-------------+----------------+
| customer_id | name | address_id | customer_id |street |
+-------------+-------+------------+-------------+----------------+
| 1 | Jack | 1 | 1 |Jack's address |
| 3 | Paul | 2 | 3 |Paul's address |
| 4 | Jacob | NULL | NULL |NULL |
+-------------+-------+------------+-------------+----------------+
Returned are all the records from the left table (customers) and the corresponding records in the right
table, which, if they do not exist, are returned as null.
26
RIGHT JOIN
27
RIGHT JOIN
+-------------+-------+------------+-------------+----------------+
| customer_id | name | address_id | customer_id |street |
+-------------+-------+------------+-------------+----------------+
| 1 | Jack | 1 | 1 |Jack's address |
| 3 | Paul | 2 | 3 |Paul's address |
| NULL | NULL | 3 | 10 |Wrong address |
+-------------+-------+------------+-------------+----------------+
28
RIGHT JOIN
+-------------+-------+------------+-------------+----------------+
| customer_id | name | address_id | customer_id |street |
+-------------+-------+------------+-------------+----------------+
| 1 | Jack | 1 | 1 |Jack's address |
| 3 | Paul | 2 | 3 |Paul's address |
| NULL | NULL | 3 | 10 |Wrong address |
+-------------+-------+------------+-------------+----------------+
Returned are all the records from the right table (customers) and the corresponding records in the left
table, which, if they do not exist, are returned as null.
29
Relations
between tables
30
One-to-one relationship
31
One-to-one relationship
The one-to-one relationship is created by making the primary key of an entry dependent on the primary
key of another object. The primary key cannot exist without this relation. In our case it will be typing the
client's primary key as the primary address key.
CREATE TABLE customers(
customer_id int NOT NULL AUTO_INCREMENT,
name varchar(255) NOT NULL,
PRIMARY KEY(customer_id)
);
CREATE TABLE addresses(
customer_id int NOT NULL, street varchar(255),
PRIMARY KEY(customer_id),
FOREIGN KEY(customer_id) REFERENCES customers(customer_id)
ON DELETE CASCADE
);
32
One-to-one relationship
The one-to-one relationship is created by making the primary key of an entry dependent on the primary
key of another object. The primary key cannot exist without this relation. In our case it will be typing the
client's primary key as the primary address key.
CREATE TABLE customers(
customer_id int NOT NULL AUTO_INCREMENT,
name varchar(255) NOT NULL,
PRIMARY KEY(customer_id)
);
CREATE TABLE addresses(
customer_id int NOT NULL, street varchar(255),
PRIMARY KEY(customer_id),
FOREIGN KEY(customer_id) REFERENCES customers(customer_id)
ON DELETE CASCADE
);
33
One-to-one relationship
The one-to-one relationship is created by making the primary key of an entry dependent on the primary
key of another object. The primary key cannot exist without this relation. In our case it will be typing the
client's primary key as the primary address key.
CREATE TABLE customers(
customer_id int NOT NULL AUTO_INCREMENT,
name varchar(255) NOT NULL,
PRIMARY KEY(customer_id)
);
CREATE TABLE addresses(
customer_id int NOT NULL, street varchar(255),
PRIMARY KEY(customer_id),
FOREIGN KEY(customer_id) REFERENCES customers(customer_id)
ON DELETE CASCADE
);
34
FOREIGN KEY
The FOREIGN KEY attribute added to a column simply says that this column indicates the primary
key of another table.
It speeds up the work of our database and makes it impossible to enter incorrect data (e.g. it will not
allow to enter a key that does not appear in the second table).
35
ON DELETE CASCADE
While building a relationship we can add the ON DELETE CASCADE option. This option causes the
deletion of record in the main table, which is indicated by foreign keys, to automatically delete all records
in other tables, which are connected to it by a relation.
For example: if we delete a user, we want all his addresses in the system to be thrown out together.
If we do not add this option, SQL will not allow us to delete a record as long as any entries in other tables
are related to it.
For example: SQL will not allow us to delete a user as long as there are records assigned to him in the
address table.
36
One-to-one relationship
INSERT INTO customers(name) VALUES ("John"), ("Jack"), ("William");
INSERT INTO addresses(customer_id, street)
VALUES (1, "John's street"), (2, "Jacob's street");
SELECT * FROM customers
JOIN addresses
ON customers.customer_id = addresses.customer_id
WHERE customers.customer_id = 2;
+-------------+------+-------------+--------------+
| customer_id | name | customer_id | street |
+-------------+------+-------------+--------------+
| 2 | Jack | 2 | Jack's street|
+-------------+------+-------------+--------------+
37
FOREIGN KEY - adding elements
SELECT * FROM customers;
+-------------+--------+
| customer_id | name |
+-------------+--------+
| 1 | John |
| 3 | William|
+-------------+--------+
38
FOREIGN KEY - adding elements
SELECT * FROM customers;
+-------------+--------+
| customer_id | name |
+-------------+--------+
| 1 | John |
| 3 | William|
+-------------+--------+
If there is no primary key in the second table that you want to refer to with an external key, then SQL will
return the error.
In our case, the customers table does not have a record customer_id=5.
39
FOREIGN KEY - deleting elements
40
FOREIGN KEY - deleting elements
41
Exercises
Exercise time
Day 2
One-to-one relationship
42
One-to-many relationship
43
One-to-many relationship
Relationship one to many is created by adding an additional column, in which we hold the primary key of
the object from the second table.
44
One-to-many relationship
INSERT INTO orders(customer_id, order_details)
VALUES(3, "Order1"), (3, "Order2"), (1, "Order3");
SELECT * FROM customers
JOIN orders
ON customers.customer_id = orders.customer_id
WHERE customers.customer_id = 3;
+-------------+--------+----------+------------+---------------+
| customer_id | name | order_id | customer_id|order_details |
+-------------+---------+----------+------------+--------------+
| 3 | William | 1 | 3|Order1 |
| 3 | William | 2 | 3|Order2 |
+-------------+---------+----------+------------+--------------+
45
Exercises
Exercise time
Day 2
One-to-many relationship
46
Many-to-many relationship
47
Many-to-many relationship
48
Many-to-many relationship
CREATE TABLE items(
item_id int NOT NULL AUTO_INCREMENT,
description varchar(255),
PRIMARY KEY(item_id)
);
INSERT INTO items(description)
VALUES ("Item 1"),
("Item 2"),
("Item 3");
49
Many-to-many relationship
CREATE TABLE items_orders(
item_id int NOT NULL,
order_id int NOT NULL,
PRIMARY KEY(id),
FOREIGN KEY(order_id) REFERENCES orders(order_id),
FOREIGN KEY(item_id) REFERENCES items(item_id)
);
50
Many-to-many relationship
CREATE TABLE items_orders(
item_id int NOT NULL,
order_id int NOT NULL,
PRIMARY KEY(id),
FOREIGN KEY(order_id) REFERENCES orders(order_id),
FOREIGN KEY(item_id) REFERENCES items(item_id)
);
The name of the auxiliary table to the relation is usually created by combining the names of 2 tables, the
relation of which we want to do many-to-many relationship.
51
Many-to-many relationship
CREATE TABLE items_orders(
item_id int NOT NULL,
order_id int NOT NULL,
PRIMARY KEY(id),
FOREIGN KEY(order_id) REFERENCES orders(order_id),
FOREIGN KEY(item_id) REFERENCES items(item_id)
);
52
Many-to-many relationship
INSERT INTO items_orders(order_id, item_id)
VALUES (1,1), (2,1), (2,2);
SELECT * FROM orders
JOIN items_orders
ON orders.order_id=items_orders.order_id
JOIN items
ON items.item_id=items_orders.item_id;
+--------+-----------+-------------+-------+--------+-------+-----------+
|order_id|customer_id|order_details|item_id|order_id|item_id|description|
+--------+-----------+-------------+-------+--------+-------+-----------+
| 1 | 3 |Order1 | 1 | 1 | 1 | Item 1 |
| 2 | 3 |Order2 | 1 | 2 | 1 | Item 1 |
| 2 | 3 |Order2 | 2 | 2 | 2 | Item 2 |
+--------+-----------+-------------+-------+--------+-------+-----------+
53
Exercises
Exercise time
Day 2
Many-to-many relationship
54
Advanced SQL
55
SQL built-in functions
SQL language also implements many functions that make it easier to work on strings, numbers and
dates.
Full list of these functions (with descriptions) can be found here:
http://www.w3schools.com/sql/sql_ref_mysql.asp
56
Indexes
Indexes are special search tables that speed up the search of a table in one of the columns.
We should use them when many WHERE clauses depend on this column.
Too many indexes can slow down the operation of the database - that's why you should pay attention to
them and add them after a thorough analysis of the database.
The operation of indexes is most visible in the query execution speed if the index is added to a column
with a numeric type.
57
Transactions
SQL also allows for transactions. This is a group of SQL queries called entirely from the database. If any
of these queries fails, the database returns to the state before the transaction.
This is an advanced mechanism, which occurs e.g. in banking systems.
A query in transactions means that all or none of the queries must be executed correctly.
More about transactions:
http://www.tutorialspoint.com/sql/sql-transactions.htm
http://www.w3resource.com/mysql/mysql-transaction.php
An example of a transaction (in SQL sense not literally) can be a currency exchange e.g. PLN -> EUR
where the balance of EUR will be credited ONLY when the balance of PLN is sufficient. Look at the code
on the next slide.
58
Transactions
An example of a transaction:
try {
$conn->beginTransaction();
$result = $conn->query("UPDATE pln_acc SET bal=bal-199 WHERE bal>=199");
if ($result->numRows() > 0){
$conn->query("UPDATE eur_acc SET bal=bal+50");
$conn->commit();
} else {
$conn->rollBack();
}
} catch (PDOException $e) {
$conn->rollBack();
echo "Error: " . $e->getMessage();
}
59
Transactions
An example of a transaction:
try {
$conn->beginTransaction();
$result = $conn->query("UPDATE pln_acc SET bal=bal-199 WHERE bal>=199");
if ($result->numRows() > 0){
$conn->query("UPDATE eur_acc SET bal=bal+50");
$conn->commit();
} else {
$conn->rollBack();
}
} catch (PDOException $e) {
$conn->rollBack();
echo "Error: " . $e->getMessage();
}
60
Transactions
An example of a transaction:
try {
$conn->beginTransaction();
$result = $conn->query("UPDATE pln_acc SET bal=bal-199 WHERE bal>=199");
if ($result->numRows() > 0){
$conn->query("UPDATE eur_acc SET bal=bal+50");
$conn->commit();
} else {
$conn->rollBack();
}
} catch (PDOException $e) {
$conn->rollBack();
echo "Error: " . $e->getMessage();
}
61
Transactions
An example of a transaction:
try {
$conn->beginTransaction();
$result = $conn->query("UPDATE pln_acc SET bal=bal-199 WHERE bal>=199");
if ($result->numRows() > 0){
$conn->query("UPDATE eur_acc SET bal=bal+50");
$conn->commit();
} else {
$conn->rollBack();
}
} catch (PDOException $e) {
$conn->rollBack();
echo "Error: " . $e->getMessage();
}
If so, we change the balance of the second currency and confirm both queries in the transaction.
62
Transactions
An example of a transaction:
try {
$conn->beginTransaction();
$result = $conn->query("UPDATE pln_acc SET bal=bal-199 WHERE bal>=199");
if ($result->numRows() > 0){
$conn->query("UPDATE eur_acc SET bal=bal+50");
$conn->commit();
} else {
$conn->rollBack();
}
} catch (PDOException $e) {
$conn->rollBack();
echo "Error: " . $e->getMessage();
}
If not, it means that we do not have sufficient funds, we revoke the transaction.
63
Transactions
An example of a transaction:
try {
$conn->beginTransaction();
$result = $conn->query("UPDATE pln_acc SET bal=bal-199 WHERE bal>=199");
if ($result->numRows() > 0){
$conn->query("UPDATE eur_acc SET bal=bal+50");
$conn->commit();
} else {
$conn->rollBack();
}
} catch (PDOException $e) {
$conn->rollBack();
echo "Error: " . $e->getMessage();
}
64
Triggers
65