Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 9 – MYSQL and PHP (Part1) SFDV3011 – Advanced Web Development 1.

Similar presentations


Presentation on theme: "Lecture 9 – MYSQL and PHP (Part1) SFDV3011 – Advanced Web Development 1."— Presentation transcript:

1 Lecture 9 – MYSQL and PHP (Part1) SFDV3011 – Advanced Web Development 1

2 2 SQL  SQL (Structured Query Language) is the language most commonly used to define, manipulate, and query RDBMSs  It’s origins trace back to SEQUEL designed for IBM’s “System R” in 1970s  Currently there is an ANSI (American National Standards Institute) standard for SQL  The standard does not adhere in many respects to the relational model described by Codd (e.g. it explicitly breaks several important relational concepts - particularly by allowing duplicate rows, and columns with the same names)

3 3 RDBMSs based on SQL  There are a number of choices for an RDBMS based on SQL: Oracle - developed by Oracle Corporation (whose origins date back to 70s, when Ellis spotted potential in concept of relational theory and IBM’s SEQUEL) Microsoft SQL Server MySQL - extremely popular, open source RDBMS PostgreSQL, SQLite,...and many others  Each of these RDBMSs uses it’s own implementation of SQL. In this course we will cover MySQL.

4 4 MYSQL  Open source RDBMS  Popular, because it’s free, lightweight (not all the features of Oracle) and relatively fast  Named after the daughter (My) of Michael Widenius, who was the main author of the first version  Used by Wikipedia, Facebook and many other websites  Managed and developed by MySQL AB until 2008 when it was acquired by SUN Microsystems, which in turn was bought by Oracle Corporation in 2010.

5 5 Example of database OrganisationIDNameAddressNotes 1ACME IncNew YorkVery friendly crew 2Abcde.comBathgateNo comment VisitIDVisitorIDOrganisationIDDate 11221/03/01 23223/07/05 32105/02/06 VisitorIDNameEmailAffiliation 1John DoeJ.d@napier.ac.ukNapier University 2Jim DoeJi.d@napier.ac.ukNapier University 3John DoeJo.d@napier.ac.ukNapier University Visitors Organisation Visits

6 6 Numeric data types BIT[(n)]1 to 2 n TINYINT-128 to 127 SMALLINT-32768 to 32767 INT-2147483648 to 2147483647 FLOAT-3.4E+38 to -1.18e-38, 0, and 1.18E-38 to 3.4E+38 BOOL, BOOLEAN – 0 = FALSE – other non null values = TRUE

7 7 String data types CHAR(n), 0< n <255 – [BINARY | ASCII | UNICODE] TINYBLOBup to 255 bytes TINYTEXTup to 255 characters BLOBup to 65535 bytes TEXTup to 65535 characters ENUM('value1', 'value2',...) up to 65535 values

8 8 Date and Time data types DATE'1000-01-01' to '9999-12-31' TIME'-838:59:59' to '838:59:59' DATETIME'1000-01-01 00:00:00' to '9999-12-31 23:59:59' TIMESTAMP used to record update or insert times YEAR [(2 | 4)]1901 to 2155,

9 9 Log in mysql Type command: mysql -h hostname -u username -p Where: hostname = localhost default username = root Once logged in, the following mysql prompt appears to type mysql commands: mysql>

10 10 Create a database  Type the command: create database dbname;  View tables created (at first there won't be any, because you haven't made any yet!) : show tables;

11 11 Create a table mysql> create table tablename( column1 type, column2 type,... columnn type); mysql> create table visitors( visitorID int unsigned not null auto_increment primary key, name char(50) not null, email char(50), Affiliation char(200)); mysql> create table organisations( organisationID int unsigned not null auto_increment primary key, name char(50) not null, address char(200), notes text); mysql> create table visits( visitID int unsigned not null auto_increment primary key, visitorID int unsigned not null, organisationID int unsigned not null, date date);

12 12 Looking at the database View all tables: – show tables; Describe a table: – describe tablename; List table content: – Query the database …

13 13 Inserting data mysql> insert into tablename [(col1, col2,...)] values (val1, val2,...); mysql> insert into visitors (name, email) values ('John Doe', 'j.d@napier.ac.uk'), ('Jim Doe', 'ji.d@napier.ac.uk'), ('Jon Doe', 'jo.d@napier.ac.uk'); mysql> insert into organisations (name, address, notes) values ('ACME', 'New York', NULL), ('abcde.com', ‘Bathgate’, 'No comment!'); mysql> insert into visits values (NULL, 1, 2, '2000-12-20'), (NULL, 2, 2, '2004-04-21'), (NULL, 1, 2, '2006-05-06');

14 14 Retrieving data SELECT [options] items [INTO file_details] FROM tables [WHERE conditions] [GROUP BY group_type] [HAVING where_definitions] [ORDER BY order_type] [LIMIT limit_criteria] [PROCEDURE procedure_name(args)] [lock_options];

15 15 Retrieving data Select whole table: – select * from table_name; Select one column: – select col_name from table_name; Select two columns: – select col1, col2 from table_name; Selection with criterion: – select * from table_name where criterion; – Note: criterion is a boolean.

16 16 Selection from multiple tables (1) Selection condition(s) may involve more than one table Example: “Show the dates of all visits made by Jim Doe.” select visits.date from visits, visitors where visitors.name = 'Jim Doe' and visitors.visitorID = visits.visitorID;

17 17 Selection from multiple tables (2) Selection from more than two tables: – Follow relations between tables Example: “Show the dates of all visits made by Jim Doe to Acme Inc.” You do it, using SELECT, FROM, WHERE, AND Answer: select visits.date from visits, visitors, organisations where visitors.name = 'Jim Doe' and visitors.visitorID = visits.visitorID and organisation.name = 'Acme Inc.' and organisation.organisationID = visits.organisationID;

18 18 Updating records UPDATE [options] tablename SET col1=expr1, col2=expr2 … [WHERE conditions] [ORDER BY order_type] [LIMIT number] Example - Update ACME’s address: update organisations set address = 'Boston' where organisationID = 1;

19 19 Deleting records DELETE [options] FROM tablename [WHERE conditions] [ORDER BY order_type] [LIMIT number] Example - Delete ACME from organisation table: delete from organisations where organisationID = 1;

20 20 Deleting tables DROP [options] TABLE tablename; Example – Delete organisations: drop table organisations;

21 21 Tips  SQL commands can be stored in a text file.  Commands stored in the text file can be executed using source Example: mysql> source filename.sql  In command windows (DOS/UNIX), use the up arrow to navigate to previously typed commands.

22 22 MYSQL storage engines  MySQL supports multiple storage engines  Each table can be configured to use a different storage engine – you can mix storage engines in one database  When you create a new table, you can specify which storage engine to use as follows: create table visits( visitID int unsigned not null auto_increment primary key, visitorID int unsigned not null, organisationID int unsigned not null, date date) ENGINE=’MyISAM ’;  It is possible to migrate a table to a different storage engine (this is not always a trivial operation, since some features might not be supported in both engines) ALTER TABLE visits ENGINE=’InnoDB ’;  To find out which storage engine a table uses: SHOW CREATE TABLE visits \G ;

23 23 MYSQL storage engines  InnoDB (default for MySQL 5.5 and later) - transaction safe (ACID compliant), data stored in clustered indexes, foreign-key support  MyISAM (default prior to MySQL 5.5) - no-transaction, full-text search index  Archive - supports only INSERT and SELECT queries; un-indexed tables for storing data that is not accessed too often  Memory - all data stored in RAM (does not survive reboot), very fast, good for intermediate results...and more

24 24 Schema optimization  Choosing data types  The smaller the data type (in terms of bytes it uses to represent information) the faster its manipulation  Simpler data types are easier to handle (e.g. storing date and time as integers, not strings)  Define fields as NOT NULL whenever you can - possibility of variable being null makes queries and indexing more complicated  Using VARCHAR instead of CHAR trades storage space for speed  It is best to use INTEGER type for primary keys

25 25 Indexing  An index is a map of your data that orders it and allows for quick search (like index at the end of a book with references to pages where a particular term can be found)  Indexes help a database retrieve data efficiently  For small databases indexing can be neglected, but as the size of the database grows, indexing becomes critical  Indexes slow down inserts and updates but speed up WHERE clauses and ORDER BY.  Failure to properly index data is the leading cause of SQL performance problems

26 26 Query performance  Poorly designed queries may unnecessarily retrieve more data than needed (not only too many rows but also too many columns) that is eventually thrown away before returning the final result  Do you need so many rows? SELECT * FROM organisation, visits WHERE organisation.OrganisationID = visits.OrganisationID LIMIT 1;  Do you need all the columns?  The EXPLAIN statement can be used as a way to obtain information about how MySQL executes a SELECT statement EXPLAIN SELECT * FROM organisation, visits WHERE organisation.OrganisationID = visits.OrganisationID;


Download ppt "Lecture 9 – MYSQL and PHP (Part1) SFDV3011 – Advanced Web Development 1."

Similar presentations


Ads by Google