Dynamic websites(lec1)

Preview:

Citation preview

Dynamic WebsitesPHP with Oracle DB By Belal Arfa

What is Relational DB?

A Database is a “Special Data Container” in which the computer stores largeamounts of data.

DB VS Files ?– Total Centralization ( Cinema Tickets )– Highest Performance Measures

( Deal with large data with no crash )– Reducing Data Redundancy

( PK and FK employees and Depts )– Better Data Security– Full Data Integrity

( Foreign Key )

Don't Worry if you didn't understand these terminologies

DB Structure ?Database is a group of logical tablesand table includes columns, indexes, foreign keys, etc...But what are tables ?this is a table

Car_Code Car_Name1001 BMW

1002 MERCEDES

1003 PORSCHE

1004 FIAT

Tables

– A Table is composed of Rows (Data in the Table) and Columns (Table's Structure)...

– A Table is used to Store data in it, in the above it is storing data about Cars Brands.

– We Can Insert, Update, Delete and Read Table's Data.

Tables

So we said that Database is a group of related and interconnected tables, HOW ???we can describe a car by Brand and Model...There is a logical connection between Brands and Models...ex.BMW Brand has many Models ( X3,X6, etc...)Mercedes Brand has many Models ( CLK, etc...)

Model_Code Brand_Code Model_Name

1 1001 X1

2 1001 X2

3 1002 C200

4 1004 128

Car_Code Car_Name1001 BMW

1002 MERCEDES

1003 PORSCHE

1004 FIAT

Tables Primary Key (Unique and Not Null)

Primary Key (Unique and Not Null)

Foreign Key (Referential Integrity)

TablesSo what are unique and not null ?UniqueCan we have 2 different brands having the same Code???Can we give BMW code 10001 and Mercedes the same?

Logically NO !!!That is what “Unique Constraint” guarantee, when you create one on a certain column.

Brand_Code Brand_Name

1001 BMW

1001 MERCEDES

TablesNot NullCan we have Brand Without a Code???Can we add a new Brand JEEP, and leave it's code blank??

NO!!!That is what “Not Null Constraint” guarantee for a certain columns you specify. It arises an error when someone inserts a Brand without inserting a code for it.

Brand_Code Brand_Name

.... .....

JEEP

Tables

Unique constraint + Not Null Constraint = Primary Key Column(s) potentially having both constraints are candidates for us to specify them as the “Primary Key” of the table. Pk combines both constraints, it uniquely identifies each Row.

TablesCan we Insert a New Model and assign it to a Non Existent Brand??

Also Can we Delete a Model who has Child Brands???

Model_Code Brand_Code Model_Name

1 1001 X!

5 9999 ABC

Brand_Code Brand_Name

1001 BMW

..... .....

TablesCertainly NO!!And This is “Data Integrity”!!!You Remember the Database Advantages we Mentioned before???This is the “Referential Integrity” we gain by adding a “Foreign Key” constraint on certain Column(s), and choosing their parents.FK guarantees child records can't be assigned to non-existent parents, and parents can't be deleted as long as they have children.

Tables From the beginning why we made a Code for each Brand??Also Why we made a Code Column for each Model???Why don't we depend on NAMES??First Because we can have the same name for different Brands/Models.Ex Fiat produced F128 model, and VOLX produced F128 model...We have to distinguish between them!!!Like the ID of a person,2 people named AbdelRahaman Omar Mohamed but they have different Ids.Second, using numbers while relating tables together minimizes “Redundancy”, we just assign the parent's code to the child records.

Designing The DatabaseNow that we understand Database concepts, Many companies developed “Relational Database Management System”,which is the Software platform we are going to implement our “Schema” on.Oracle, MySQL and Microsoft SQL Server are such RDBMS...So to implement the Schema which is the set of table we will create, we are going to use Oracle Database Engine.You can Implement the same by using different engines with very slight difference!!!!All RDBMS Implement the same functionality with slight difference in code syntax.

Designing The Database

To interact with the DB engine you will write “Structured Query Language”.“SQL” is the programming language used to interact with a DB Engine. With SQL code, we canCreate, Modify (Alter) and Drop the Database Structure (DDL)....CRUD: Create, Read, Update, Delete Data (DML)...

Designing The DatabaseWe will Learn SQL by Example...You should install Oracle Express Edition..Also you should open the SQL Developer, create a new connection with the User-name system and the password you specified during installation as illustrated.Host Name refers to the server the Oracle Database Engine is installed at.In our case it's localhost (the same computer), else insert the ip of the server you installed Oracle at.SID is xe (Express Edition), else if you installed an Oracle Standard/Enterprise usually it would be orcl.

Designing The Database

DDL

DDLCreate, Drop and Alter( Modify ) tables.Before creating a table take care of: 1- Table Name 2- Columns Names 3- Columns Types 4- Which Column will be PK

ExampleCreate Table Persons( P_Id number(20), LastName varchar2(50) NOT NULL, FirstName varchar2(50), Address varchar2(50),

CONSTRAINT PERSON_PK PRIMARY KEY (p_id)) Drop TableDrop Table Persons;Alter Table ( Add Column ) Alter Table Persons Add weight number(20,10);Remove Column Alter Table Persons Drop column weight ;

DML

DMLCRUD Create, Read, Update and Delete.

● INSERT INTO - Create new data into a database.● SELECT - Read data from a database.● UPDATE - Updates data in a database.● DELETE - Deletes data from a database.

Insert StmtSyntax-Insert Into table_name( col1, col2, col3,.... ) values( value1, value2, value3,.... ) .-Insert Into table_name values( value1, value2, value3,.... ) -- all column vals is a mustex:-insert into persons values(1,'Arfa','Belal','Egypt');-insert into persons (p_id,lastname)values(2,'Omar');

Select StmtSyntaxSELECT [all|distinct] column_name(s) FROM table_nameWHERE search_conditionex- Select * from persons;- Select firstname, lastname from persons;- Select Distinct address from persons;- Select * from persons WHERE address='Egypt';- Select * from persons where weight > 50;

Select StmtOperators

Operator Description

= Equal

<> Not Equal

> Greater Than

< Less Than

>= Greater Than or Equal

=< Less Than or Equal

LIKE Search for a pattern

BETWEEN Between inclusive range

IN in specific values

Select StmtLogic Operators ( The AND & OR Operators )The AND operator displays a record if both the first condition and the second condition is true.The OR operator displays a record if either the first condition or the second condition is true.ex- Select * from persons where firstname = 'Belal' and lastname='Arfa';- Select * from persons where lastname = 'Arfa' or lastname ='Omar';

Order By ClauseSyntaxSELECT column_name(s)FROM table_nameORDER BY column_name(s) ASC|DESCexSelect * from persons ORDER by firstname;

Update StmtSyntaxUPDATE table_nameSET column1=value, column2=value2,...WHERE some_column=some_value;

Note: Notice the WHERE clause in the UPDATE syntax. The WHERE clause specifies which record or records that should be updated. If you omit the WHERE clause, all records will be updated!

exUpdate persons set lastname = 'Mohamed' where p_id=1;Update persons set address = 'Cairo'; -- will update all table data

Delete StmtSyntaxDELETE FROM table_nameWHERE some_column=some_value;

Note: Notice the WHERE clause in the DELETE syntax. The WHERE clause specifies which record or records that should be deleted. If you omit the WHERE clause, all records will be deleted!

Delete from persons where p_id=1;Delete from persons; -- will delete all table data

ExamplesSchema:- Departments ( id, name );- Employees ( id, name, dept );get each employee name and his corresponding dept.

SolSelect e.name, d.namefrom employees e , departments dwhere e.dept = d.pk

Examples

SolSELECT S.snameFROM Sailors S, Reserves RWHERE S.sid = R.sid AND R.bid = 103

Schema:- Sailors (sid, sname, rating, age)- Boats (bid, bname, color)- Reserves (sid, bid, day)- Find the names of sailors who have reserved boat #103

ExamplesSchema:

- Sailors (sid, sname, rating, age)- Boats (bid, bname, color)- Reserves (sid, bid, day)- Find the colors of boats reserved by a sailor named rusty

SolSELECT B.colorFROM Sailors S, Reserves R, Boats BWHERE S.sid = R.sid AND R.bid = B.bid AND S.sname = ‘rusty’

ExamplesSELECT S.sname, S.age, S.ratingFROM Sailors SORDER BY S.age ASC, S.rating DESC

What does this query compute?

SolFind the names, ages, and rankings of all sailors.Sort the result in increasing order of age.If there is a tie, sort those tuples in decreasing order of rating.

ExamplesFind names of sailors who have reserved a red or a green boat ?

SolSELECT S.sname FROM Sailors S, Reserves R, Boats BWHERE S.sid = R.sid AND R.bid = B.bid AND (B.color = ‘red’ OR B.color = ‘green’)

Another SolSELECT S.sname FROM Sailors S, Reserves R, Boats BWHERE S.sid = R.sid AND R.bid = B.bid AND B.color = ‘red’UNIONSELECT S.sname FROM Sailors S, Reserves R, Boats BWHERE S.sid = R.sid and R.bid = B.bid AND B.color = ‘green’

ExamplesSELECT S.sname FROM Sailors SWHERE S.sid IN ( SELECT R.sid FROM Reserves R

WHERE R.bid=103 )

What does this query compute?

Solget all sailors who had reserved boat no. 103

To find sailors who have not reserved 103, use NOT IN

Examples- User (uid, username, age, hometown)- Network (nid, description, networkname)- Member (uid, nid)- Friend (uid1, uid2)Find the names and ages of all users belonging to a networknamed ‘Michigan’ in decreasing order of Age

SolSELECT U.username, U.ageFROM User U, Network N, Member MWHERE U.uid = M.uid AND N.nid = M.nidAND N.networkname = ‘Michigan’ORDER BY U.age DESC

ExamplesFind the names of all users who are friends withthe user with uid 456 (omit duplicates)

SolSELECT DISTINCT U2.usernameFROM User U, Friend FWHERE F.uid1 = 456 AND F.uid2 = U2.uid

Aggregation FunctionsPerform calculation on a set of values and return single value.SyntaxSelect Function(column) fromtable

Name SalaryMohamed 4000

Hassan 3000

Doaa 6000

Ahmed 4000

Aggregation FunctionsRequirements Select Stmt Result

Average of salary Select AVG(salary) from employees; 4250

Number of Rows Select COUNT(*) from employees; 4

Distinct Salaries Select COUNT(Distinct Salary) from employees; 3

Highest Salary Select MAX(salary) from employees; 6000

Lowest Salary Select MIN(salary) from employees; 3000

Total Salaries Select SUM(salary) from employees; 17000

To Do

Search for Agg functions.Search for Group By clause.Search for Having clause.

Thank You