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

PHP 08 MySQL

give me multiple questions

Uploaded by

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

PHP 08 MySQL

give me multiple questions

Uploaded by

tuqamazin13
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 58

Introduction to MySQL

Web application development 2-BIT481

To be used in assocition with the book:


PHP, MySql, and JavaScript by Robin Nixon
Unless otherwise noted, the content of this course material is licensed under a Creative
Commons Attribution 3.0 License.
http://creativecommons.org/licenses/by/3.0/.

Copyright 2011-12, Charles Severance


Relational Databases
Relational databases model data by
storing rows and columns in tables. The
power of the relational database lies in its
ability to efficiently retrieve data from
those tables and in particular where there
are multiple tables and the relationships
between those tables involved in the
query.

http://en.wikipedia.org/wiki/Relational_database
Terminology
• Database - Contains many tables
• Relation (or table) - contains tuples and attributes
• Tuple (or row) - is a set of fields it generally represents
an “object” like a person or a music track

• Attribute (also column or field) - One of possibly many


elements of data corresponding to the object
represented by the row
A relation is defined as a set of tuples that have the same attributes. A tuple
usually represents an object and information about that object. Objects are
typically physical objects or concepts. A relation is usually described as a
table, which is organized into rows and columns. All the data referenced by an
attribute are in the same domain and conform to the same constraints. (
wikipedia)
Columns / Attributes

Rows /
Tuples

Tables / Relations
Two Roles in Large Projects
• Application Developer - Builds the logic for the
application, the look and feel of the application -
monitors the application for problems

• Database Administrator - Monitors and adjusts the


database as the program runs in production

• Often both people participate in the building of the


“Data model”
Application Structure

End Application SQL


Database
User Software Data Model

SQL

Developer
Database
DBA Tools
Database Administrator
(dba)
A database administrator (DBA) is a person
responsible for the design, implementation,
maintenance and repair of an organization's
database. The role includes the development and
design of database strategies, monitoring and
improving database performance and capacity, and
planning for future expansion requirements. They
may also plan, co-ordinate and implement security
measures to safeguard the database.

http://en.wikipedia.org/wiki/Database_administrator
Database Model
A database model or database schema is
the structure or format of a database,
described in a formal language supported by
the database management system, In other
words, a "database model" is the application
of a data model when used in conjunctio
n with a database management system.

http://en.wikipedia.org/wiki/Database_model
SQL
• Structured Query Language is the language we use to
issue commands to the database

• Create a table
• Retrieve some data
• Insert data
• Delete data
http://en.wikipedia.org/wiki/SQL
Common Database Systems
• Three Major Database Management Systems in wide use
• MySQL - Simple fast and scalable - commercial open source
• Oracle - Large, commercial, enterprise-scale, very very
tweakable

• SqlServer - Very nice - from Microsoft (also Access)


• Many other smaller projects, free and open source
• HSQL, SQLite, Postgress, ...
Communicating with MySQL

• We need some kind of interface so we can type SQL


commands

• Command line
• Full Screen
Application Structure

End Application SQL


Database
User Software Data Model

SQL

Developer
Database
DBA Tools
Command Line (XAMPP)

• After XAMPP Control Panel is Running...


• Macintosh
• /Applications/xampp/xamppfiles/bin/mysql -uroot -p
• Windows
• c:\xampp\mysql\bin\mysql.exe
Your first MySQL Command

• Kind of like "print 'hello world'"


• show databases;
If this does not work,
stop and figure out why.

Some of these are part of


MySQL and store internal
data - don't mess with them.
Creating a Database

• CREATE DATABASE publications;


• GRANT ALL ON publications.* TO jim@localhost
IDENTIFIED BY 'password';

• USE publications;
Application Structure
account / pw
End Application SQL
Database
User Software Data Model

account / pw SQL

Developer
Database
DBA Tools
Creating a Table
CREATE TABLE classics (
author VARCHAR(128),
title VARCHAR(128),
type VARCHAR(16), year CHAR(4))
ENGINE MyISAM;

DESCRIBE classics;
Data Types

• Text fields (small and large)


• Binary fields (small and large)
• Numeric fields
• AUTO_INCREMENT fields
Text Fields
• Understand character sets and indexable for searching
• CHAR allocates entire space (faster for small strings
where length is known)

• VARCHAR allocates variable amount of space depending


on the data length (less space)
Binary Types (rarely used)
• Character = 8 - 32 bits of information depending on character set
• Byte = 8 bits of information
• Small Images - data
Text Fields

• Have a character set


Binary Large Object
(BLOB)
• Large raw data, files, images, word documents, PDF,
Movies, etc etc..

• No translation, indexing or character set

http://www.youtube.com/watch?v=XhyRpvgm0
Numbers

• Numbers are very


efficient, take little
storage and are
easy to process
32 bit
because CPU's can
compare them 64 bit
often with a single
instruction
Dates

• TIMESTAMP is very efficient but only can handle


dates from 1970 through 2037

32 bit
AUTO_INCREMENT
DROP TABLE classics;
• Often as we make
multiple tables and need CREATE TABLE classics (
to JOIN them together we id INT UNSIGNED NOT NULL
need an integer, primary AUTO_INCREMENT KEY,
key for each row so we author VARCHAR(128),
can efficiently add a title VARCHAR(128),
reference to a row in a type VARCHAR(16), year CHAR(4
table, in some other ENGINE MyISAM;
table as a foreign key
DESCRIBE classics;
Inserting...
INSERT INTO classics(author, title, type, year)
VALUES('Mark Twain','The Adventures of Tom Sawyer','Fiction','1876');INSERT INTO
classics(author, title, type, year)
VALUES('Jane Austen','Pride and Prejudice','Fiction','1811');INSERT INTO classics(author,
title, type, year)
VALUES('Charles Darwin','The Origin of Species','Non-Fiction','1856');INSERT INTO
classics(author, title, type, year)
VALUES('Charles Dickens','The Old Curiosity Shop','Fiction','1841');INSERT INTO
classics(author, title, type, year)
VALUES('William Shakespeare','Romeo and Juliet','Play','1594');
Inserted...

mysql> select * from classics;+----+---------------------+------------------------------+-------------+------+| id |


author | title | type | year |+----+---------------------
+------------------------------+-------------+------+| 1 | Mark Twain | The Adventures of Tom Sawyer
| Fiction | 1876 || 2 | Jane Austen | Pride and Prejudice | Fiction | 1811 || 3 |
Charles Darwin | The Origin of Species | Non-Fiction | 1856 || 4 | Charles Dickens | The
Old Curiosity Shop | Fiction | 1841 || 5 | William Shakespeare | Romeo and Juliet |
Play | 1594 |+----+---------------------+------------------------------+-------------+------+5 rows in set
(0.00 sec)mysql>
mysql> describe classics;+--------+------------------+------+-----+---------+----------------+| Field | Type
| Null | Key | Default | Extra |+--------+------------------+------+-----+---------+----------------+|
id | int(10) unsigned | NO | PRI | NULL | auto_increment || author | varchar(128) | YES |
| NULL | || title | varchar(128) | YES | | NULL | || type | varchar(16)
| YES | | NULL | || year | char(4) | YES | | NULL | |+--------
+------------------+------+-----+---------+----------------+5 rows in set (0.00 sec)mysql> ALTER TABLE
classics MODIFY year SMALLINT;Query OK, 5 rows affected (0.08 sec)Records: 5 Duplicates: 0
Warnings: 0mysql> describe classics;+--------+------------------+------+-----+---------+----------------+|
Field | Type | Null | Key | Default | Extra |+--------+------------------+------+-----+---------
+----------------+| id | int(10) unsigned | NO | PRI | NULL | auto_increment || author |
varchar(128) | YES | | NULL | || title | varchar(128) | YES | | NULL |
|| type | varchar(16) | YES | | NULL | || year | smallint(6) | YES | |
NULL | |+--------+------------------+------+-----+---------+----------------+5 rows in set (0.00
sec)
mysql> ALTER TABLE classics ADD pages SMALLINT;Query OK, 5 rows affected (0.12
sec)Records: 5 Duplicates: 0 Warnings: 0mysql> describe classics;+--------+------------------+------
+-----+---------+----------------+| Field | Type | Null | Key | Default | Extra |+--------
+------------------+------+-----+---------+----------------+| id | int(10) unsigned | NO | PRI | NULL |
auto_increment || author | varchar(128) | YES | | NULL | || title | varchar(128)
| YES | | NULL | || type | varchar(16) | YES | | NULL | || year |
smallint(6) | YES | | NULL | || pages | smallint(6) | YES | | NULL |
|+--------+------------------+------+-----+---------+----------------+6 rows in set (0.08 sec)mysql>
Indexes
• As a table gets large (they always do) scanning all the
data to find a single row becomes very costly

• When [email protected] logs into FaceBook, they


must find my password amongst 500-million users

• There are techniques to greatly shorten the scan as long


as you create data structures and maintain those
structures - like shortcuts

• Hashes or Trees
Hashes
A hash function is any algorithm or
subroutine that maps large data sets to
smaller data sets, called keys. For
example, a single integer can serve as an
index to an array (cf. associative array).
The values returned by a hash function
are called hash values, hash codes, hash
sums, checksums or simply hashes.
Hash functions are mostly used to
accelerate table lookup or data
comparison tasks such as finding items in
a database...
http://en.wikipedia.org/wiki/Hash_functio
B-Trees
In computer science, a B-tree is a tree data structure that keeps data sorted
and allows searches, sequential access, insertions, and deletions in
logarithmic amortized time. The B-tree is optimized for systems that read
and write large blocks of data. It is commonly used in databases and
filesystems.

http://en.wikipedia.org/wiki/B-tree
MySQL Index Types
• INDEX - Good for individual row lookup and sorting /
grouping results - works best with exact matches or
prefix lookups

• PRIMARY KEY - Very little space, very very fast, exact


match, requires no duplicates, extremely fast for integer
fields

• FULLTEXT - Costly to maintain on insert of new data, can


handle substrings and the LIKE clause
FULLTEXT Details
• FULLTEXT indexes can be used only with tables that use
the MyISAM engine. (ALTER TABLE tablename ENGINE =
MyISAM;)

• FULLTEXT indexes can be created for CHAR, VARCHAR,


and TEXT columns only.

• For large data sets, it is much faster to load your data


into a table that has no FULLTEXT index and then create
the index than to load data into a table that has an
existing FULLTEXT index.
Adding Indexes

• You can cadd an index as part of a CREATE TABLE


sequence or separately using an ALTER TABLE

• ALTER TABLE classics ADD INDEX(author);


• ALTER TABLE classics ADD FULLTEXT(title);
Retrieving rows with SELECT

mysql> select * from classics;+----+---------------------+------------------------------+-------------+------+-------+| id |


author | title | type | year | pages |+----+---------------------+------------------------------
+-------------+------+-------+| 1 | Mark Twain | The Adventures of Tom Sawyer | Fiction | 1876 | NULL
|| 2 | Jane Austen | Pride and Prejudice | Fiction | 1811 | NULL || 3 | Charles Darwin | The
Origin of Species | Non-Fiction | 1856 | NULL || 4 | Charles Dickens | The Old Curiosity Shop |
Fiction | 1841 | NULL || 5 | William Shakespeare | Romeo and Juliet | Play | 1594 | NULL |
+----+---------------------+------------------------------+-------------+------+-------+5 rows in set (0.00 sec)mysql>
Retrieving rows with SELECT

mysql> select title, year from classics;+------------------------------+------+| title


| year |+------------------------------+------+| The Adventures of Tom Sawyer | 1876 ||
Pride and Prejudice | 1811 || The Origin of Species | 1856 || The Old Curiosity
Shop | 1841 || Romeo and Juliet | 1594 |+------------------------------+------+5
rows in set (0.00 sec)
mysql>
Counting with SELECT

mysql> select count(*) from classics;+----------+| count(*) |+----------+| 5 |+----------


+1 row in set (0.00 sec)mysql>
WHERE Clause
• We can limit the rows we retrieve on a SELECT using a
WHERE clause

mysql> SELECT title, author, year FROM classics WHERE year >
1850;+------------------------------+----------------+------+| title | author
| year |+------------------------------+----------------+------+| The Adventures of Tom
Sawyer | Mark Twain | 1876 || The Origin of Species | Charles Darwin |
1856 |+------------------------------+----------------+------+2 rows in set (0.00
sec)mysql>
The LIKE clause
• We can do wildcard matching in a WHERE clause using
the LIKE operator

mysql> SELECT title, author FROM classics WHERE title LIKE "%and%";
+---------------------+---------------------+| title | author |
+---------------------+---------------------+| Pride and Prejudice | Jane Austen ||
Romeo and Juliet | William Shakespeare |+---------------------+---------------------+2
rows in set (0.00 sec)mysql>
ORDER BY

mysql> SELECT title, author, year FROM classics ORDER BY year;


+------------------------------+---------------------+------+| title | author
| year |+------------------------------+---------------------+------+| Romeo and Juliet
| William Shakespeare | 1594 || Pride and Prejudice | Jane Austen |
1811 || The Old Curiosity Shop | Charles Dickens | 1841 || The Origin of
Species | Charles Darwin | 1856 || The Adventures of Tom Sawyer | Mark
Twain | 1876 |+------------------------------+---------------------+------+5 rows in set
(0.00 sec)mysql>
ORDER BY

mysql> SELECT title, author, year FROM classics ORDER BY year DESC;
+------------------------------+---------------------+------+| title | author
| year |+------------------------------+---------------------+------+| The Adventures of
Tom Sawyer | Mark Twain | 1876 || The Origin of Species | Charles
Darwin | 1856 || The Old Curiosity Shop | Charles Dickens | 1841 ||
Pride and Prejudice | Jane Austen | 1811 || Romeo and Juliet |
William Shakespeare | 1594 |+------------------------------+---------------------+------+5
rows in set (0.00 sec)mysql>

Indexes improve ORDER BY performance


The LIMIT Clause
• The LIMIT clause can request the first "n" rows, or the first "n"
rows after some starting row. Note: the first row is zero, not one

• WHERE and ORDER BY clauses happen *before* the LIMIT is


applied

mysql> SELECT title, author, year FROM classics ORDER BY year DESC LIMIT
2;+------------------------------+----------------+------+| title | author | year |
+------------------------------+----------------+------+| The Adventures of Tom Sawyer | Mark Twain |
1876 || The Origin of Species | Charles Darwin | 1856 |+------------------------------
+----------------+------+2 rows in set (0.01 sec)
The LIMIT Clause
• The LIMIT clause can request the first "n" rows, or the first "n"
rows after some starting row. Note: the first row is zero, not one

• WHERE and ORDER BY clauses happen *before* the LIMIT is


applied

mysql> SELECT title, author, year FROM classics ORDER BY year DESC LIMIT
1,2;+------------------------+-----------------+------+| title | author | year |
+------------------------+-----------------+------+| The Origin of Species | Charles Darwin | 1856 ||
The Old Curiosity Shop | Charles Dickens | 1841 |+------------------------+-----------------+------+2
rows in set (0.00 sec)
GROUP BY and COUNT
• We can get sub-counts of items where there are
duplicate values in a column

INSERT INTO tracks (title, rating) VALUES ('Who


Made Who', 5);INSERT INTO tracks (title, rating)
CREATE TABLE tracks ( id INT UNSIGNED VALUES ('Stray Cat Strut', 4);INSERT INTO
NOT NULL AUTO_INCREMENT KEY, title tracks (title, rating) VALUES ('The Twist',
VARCHAR(128), rating INTEGER); 2);INSERT INTO tracks (title, rating) VALUES
('Down With The Sickness', 4);INSERT INTO
tracks (title, rating) VALUES ('Iron Man', 5);
UPDATE .. SET
• Allows the updating of one or more columns in a row or
set of rows

• Usually used with a WHERE clause


mysql> SELECT * FROM tweet;
+----------------+-------+| text | zip |
+----------------+-------+| Had pizza |
48842 || Had Chi Dog | 48109 || Went to
572 | 48109 || Coding at home | 48842 |
+----------------+-------+
mysql> UPDATE tweet SET zip='49277' WHERE text = 'Had pizza';Query
OK, 1 row affected (0.00 sec)Rows matched: 1 Changed: 1 Warnings:
0mysql> SELECT * FROM tweet;+----------------+-------+| text | zip |
+----------------+-------+| Had pizza | 49277 || Had Chi Dog | 48109 ||
Went to 572 | 48109 || Coding at home | 48842 |+----------------+-------+
JOIN

• We can pull "composite" rows from multiple tables as


long as we have fields that can link rows from one table
to the corresponding rows in another table.

http://en.wikipedia.org/wiki/Join_(SQ
mysql> select * from tweet; mysql> select * from zips;+-------
+----------------+-------+| text | +-----------+-------+| zip | city |
zip |+----------------+-------+| Had state |+-------+-----------+-------+|
pizza | 48842 || Had Chi Dog | 48842 | Holt | MI || 48109 | Ann
48109 || Went to 572 | 48109 || Arbor | MI |+-------+-----------+-------
Coding at home | 48842 | +
+----------------+-------+

mysql> SELECT * FROM tweet JOIN zips ON tweet.zip = zips.zip;


+----------------+-------+-------+-----------+-------+| text | zip | zip |
city | state |+----------------+-------+-------+-----------+-------+| Had pizza
| 48842 | 48842 | Holt | MI || Had Chi Dog | 48109 | 48109 | Ann
Arbor | MI || Went to 572 | 48109 | 48109 | Ann Arbor | MI || Coding
at home | 48842 | 48842 | Holt | MI |+----------------+-------+-------
+-----------+-------+
mysql> SELECT * FROM tweet JOIN zips ON tweet.zip = zips.zip;
+----------------+-------+-------+-----------+-------+| text | zip | zip | city
| state |+----------------+-------+-------+-----------+-------+| Had pizza |
48842 | 48842 | Holt | MI || Had Chi Dog | 48109 | 48109 | Ann
Arbor | MI || Went to 572 | 48109 | 48109 | Ann Arbor | MI || Coding
at home | 48842 | 48842 | Holt | MI |+----------------+-------+-------
+-----------+-------+

mysql> SELECT text, city, state FROM tweet JOIN zips


ON tweet.zip = zips.zip;+----------------+-----------+-------+| text
| city | state |+----------------+-----------+-------+| Had pizza | Holt
| MI || Had Chi Dog | Ann Arbor | MI || Went to 572 | Ann Arbor | MI
|| Coding at home | Holt | MI |+----------------+-----------+-------+
MySQL Functions

• Many operations in MySQL need to use the built-in


functions

• http://dev.mysql.com/doc/refman/5.0/en/string-
functions.html

• http://dev.mysql.com/doc/refman/5.0/en/date-and-time-
functions.html
Summary

• We have whipped through the basics of using MySQL


• Table creating and maintenance
• Data types
• Indexes
• SQL operations

You might also like