You are on page 1of 105

Contents at a Glance

 Part 1: MySQL Foundation

 Part 2: Creating a New Database

 Part 3: Basic SQL

 Part 4: Advance SQL

 Part 5: Managing User Access

 Part 6: New Features in MySQL 5.0

 Part 7: Interfacing with MySQL


Part 1:
MySQL
Foundations
What’s MySQL

 MySQL is a powerful relational database


management system that supports a richly featured
SQL language.

 It’s fast, easy to use and best of all, it’s free!

 MySQL is a very popular choice for web


development because of its close relationship with
PHP. Many companies provide MySQL as part of a
standard web hosting deal.
Why Use MySQL?

 You can choose from many different RDBMS options, so


why we use MySQL over another systems?

- Cost
 Commercial License Also Available for Mission Critical Systems

- Open Source
- Cross Platform
- Powerful
- Web Based Compatibility
Obtaining MySQL

 The main downloads page for MySQL is


http://www.dev.mysql.com/downloads

 This page tells you the latest major release version


and provides a link to the next step of the
download.
Installing MySQL

 Linux Installation:

 Use the rpm command with the i switch to install the


RPM packages. If you have download several
packages, you can install them together by using
the following command:

 $ rpm i MySQL*.rpm
Installing MySQL

 Windows Installation:

 Two different windows installer programs are


available for MySQL: the full distribution and a
version called Windows Essential that includes only
the most popular features.

 Also you can simply download and install WAMP


Server or XAMP Server that do not need any extra
configurations.
MySQL Interfaces

 Command Line Interface


 Default Interface
 Powerful
 Flexible
 MySQL Console

 Graphical User Interface


 Fast
 Easy
 Limited Features
 phpMyAdmin
Sample Database

 As you follow each lesson, you are strongly


encouraged to try out each example on your own
MySQL Server.

 Book Sample Table Scripts

 Type the commands and execute them

 Northwind Exported Database File

 Import northwind.sql to your MySQL Server


Connecting to MySQL

 mysql --user=username --password=password

 mysql --user=username --password

 mysql -uusername -p

 mysql --host=server (Default: localhost)

 mysql --port=port number (Default: 3306)

 Mysql -- user =root


Getting Information

 mysql> Show Databases;

 mysql> Show tables from DBname;

 mysql> Show tables;

 mysql> Show columns from tablename;

 mysql> Describe tablename;

 mysql> Status (\s)


Creating a New Table

 mysql> CREATE TABLE tablename (Field1 Data type, Field2


Data type, Field n Data type)

 Naming Rules:

 64 Character Maximum allowed for table name


 Table name can contain any character except \
and /
 Enclose field name with “ or ‘ if it contain a space
 Field name cannot be one of SQL keywords
Set Constraint on Fields

 You can add constraints to fields after it’s data type

 PRIMARY KEY
 UNIQUE
 NOT NULL
 DEFAULT
 CHECK
 AUTO_INCREMENT:
 mysql> ALTER TABLE tablename add AUTO_INCREMENT
= number
Temporary Tables

 A temporary table lasts only for the current MySQL


session.

 Therefore, after you have been disconnected from


the database, the table will no longer be available
after you reconnect.

 mysql> CREATE TEMPORARY TABLE tablename


Create Table based
on a Query

 mysql> CREATE TABLE tablename AS SELECT field(s)


FROM tablename WHERE field Operator Value

 All the specified fields will copied to the new table

 Remember the following considerations:


 Keys are not copied in this method
 Previous Auto Increment field is no longer Auto
Increment
 Data types and Not null constraint will retain
Storage Engines

 MySQL supports several different storage engines that are used to handle different
table types
 --------
 ( MEMORY , InnoDB , MyISAM , BLACKHOL , MRG_MYIS
 CSV , ARCHIVE )

 MyISAM (Default): Tables stored on disk in three files with these extensions: .MYI, .MYD,
.frm (High Speed Storage)
 InnoDB: Alternative disk based table handler that supports extra features than MyISAM
(Fast Transactional)
 Memory: Very fast storage engine that store tables in memory only, usually used for
temporary tables

 mysql> CREATE TABLE tablename (fields) ENGINE = type


Altering Tables

 mysql> ALTER TABLE tablename ADD fieldname


data type FIRST|AFTER fieldname

 mysql> ALTER TABLE tablename CHANGE


oldfieldname newfieldname data type

 mysql> ALTER TABLE tablename DROP fieldname

 mysql> RENAME TABLE oldname TO newname


Dropping Tables

 mysql> DROP TABLE tablename

 mysql> DROP TABLE IF EXISTS tablename

 Do you want to empty a table?

 mysql> TRUNCATE TABLE tablename


Defining Primary Keys

 You can define P.K when creating a table, both in


front of field name and at the end of table
definition.

 mysql> ALTER TABLE tablename ADD PRIMARY KEY


(fieldname)

 mysql> ALTER TABLE tablename DROP PRIMARY KEY


Compound Primary Keys

 mysql> CREATE TABLE tablename


(
fields definition,
CONSTRAINT P.K name PRIMARY KEY (field 1, field 2)
)

 mysql> ALTER TABLE tablename


ADD CONSTRAINT P.K name PRIMARY KEY (field 1, field 2)

 mysql> ALTER TABLE tablename DROP CONSTRAINT P.K name


Defining Foreign Keys

 mysql> CREATE TABLE tablename


(
fields definition,
FOREIGN KEY (F.K fieldname) REFERENCES maintable
(P.K fieldname)
)

 mysql> ALTER TABLE tablename ADD FOREIGN KEY (F.K


name) REFERENCES Persons (P.K name)

 mysql> ALTER TABLE tablename DROP FOREIGN KEY


Referential Integrity

 ALTER TABLE tablename ADD FOREIGN KEY (fieldname) REFERENCES


maintable (P.K name) ON UPDATE action ON DELETE action

 Actions:
 CASCADE
 SET NULL
 NO ACTION (Default)

 Note: If you do not use database level foreign key constraint, you
must ensure that your application will maintain referential integrity!
Indexes

 mysql> CREATE INDEX indexname ON


tablename(fieldname)

 mysql> ALTER TABLE tablename ADD INDEX


(fieldname)

 mysql> SHOW INDEXES FROM tablename

 mysql> SHOW KEYS FROM tablename


Indexes

 Partial Index:
 mysql> CREATE INDEX indexname ON tablename
(fieldname (number))
 mysql> ALTER TABLE tablename ADD INDEX
(fieldname(number))

 Compound Index:
 mysql> CREATE INDEX indexname ON tablename (field
1, field 2)
 mysql> ALTER TABLE tablename ADD INDEX (field 1, field
2)
Dropping Indexes

 mysql> DROP INDEX indexname ON tablename

 mysql> ALTER TABLE tablename DROP INDEX


indexname
Part 3:
Basic SQL
The Select Statement

 mysql> SELECT fieldname FROM tablename

 mysql> SELECT field1,field2,field3,fieldn FROM tablename

 mysql> SELECT * FROM tablename

 mysql> SELECT DISTINCT fieldname FROM tablename

 * Table names are case sensitive, Field names are not!


Filtering Data: WHERE

 mysql> SELECT field(s) FROM tablename WHERE field operator


value

 String Value should delimit with qoutes

 Value can be another field name

* Why number values don’t need to delimit with


qoutes?!
Operators in Where
Clause
 Relational Operators:
 =
 <>
 >, >=
 <, <=
 LIKE (Wildcards: % , _)
 Logical Operators:
 AND
 OR
 NOT
Sorting Data: ORDER BY

 mysql> SELECT field(s) FROM tablename ORDER BY


fieldname

 mysql> SELECT field(s) FROM tablename ORDER BY


field 1, field 2, field n

 mysql> SELECT field(s) FROM tablename ORDER BY


fieldname ASC|DESC
Combining Where
Clauses
 mysql> SELECT * FROM tablename WHERE field 1 Operator Value1
AND|OR field 2 Operator Value2

 Filtering on multiple values:


 mysql> SELECT * FROM tablename WHERE fieldname IN (‘Value 1’,
‘Value 2’)

 Filtering between values:


 mysql> SELECT * FROM tablename WHERE fieldname BETWEEN
Value 1 AND Value 2

* MySQL uses only parenthesis


Operator Precedence

 Consider this example:


 mysql> SELECT * FROM customer WHERE cust_id = ‘1001’ AND
first_name = ‘Albert’ OR first_name = ‘John’;
 What is the result?!

1- AND
2- OR
3- NOT

 Also you can override this precedence!


Use parenthesis
Limiting the Result

 mysql> SELECT * FROM tablename LIMIT number

 mysql> SELECT * FROM tablename LIMIT offset, number

 You can simply use this features to determine a record


with the maximum value of a specific attribute. Like
this:
 mysql> Select * FROM tablename ORDER BY fieldname
DESC LIMIT 1
The Insert Statement

 mysql> INSERT INTO tablename VALUES (value1, value2,


value3, value n)
 Delimit the string and character values by ‘

 mysql> INSERT INTO tablename (field1, field2, field3,


field n) VALUES (value1, value2, value3, value n)

 mysql> INSERT INTO tablename (fields) VALUES (value1,


value2, value3), (value1, value2, value3), (value1,
value2, value3)
Load Data from a File

 mysql> LOAD DATA INFILE path INTO TABLE tablename

 mysql> LOAD DATA INFILE path INTO TABLE tablename


FIELDS TERMINATED BY ‘symbol’ ENCLOSED BY ‘symbol’
(field 1, field 2, field n)

 mysql> LOAD DATA INFILE path INTO TABLE tablename


FIELDS TERMINATED BY ‘symbol’ ENCLOSED BY ‘symbol’
IGNORE number LINES (field 1, field 2, field n)
The Delete Statement

 DELETE FROM tablename WHERE field = value

 Remember: Always make sure that you include a


WHERE clause in a DELETE statement, otherwise you
will delete the whole data!
The Update Statement

 mysql> UPDATE tablename SET fieldname = value


WHERE fieldname = value

 Note: Without a WHERE clause, UPDATE performs the


same update on every row in the table!

 Alternative INSERT Syntax:


 mysql> INSERT INTO tablename SET field1 = value1,
field2 = value2, field n = value n
The Replace Statement

 It’s never causes a primary key violation.


 The actual behavior of replace is to execute a delete
operation with the given primary key value and then
perform an insert.
 It does not perform an update.

 mysql> REPLACE INTO tablename (field1, field2, fieldn)


VALUES (value1, value2, value n)

 Also you can use alternative insert!


Part 4:
Advanced SQL
Using Sub Queries

 A sub query is a query that is embedded within


another query

 Sub queries are sometimes also referred to as sub


select because one select statement appears
within another

 mysql> SELECT fields FROM tablename WHERE field


operator (another SELECT query)
Joining Tables

 SQL joins are used to query data from two or more tables,
based on a relationship between certain columns in these
tables

 mysql> SELECT field1, field2, field3 FROM table1, table2, table n


 Cross Join

 mysql> SELECT field1, field2 FROM table1, table2 WHERE


table1.field1 = table2.field2
 Inner Join
Advanced Join

 You learned how to simply join two or more


database tables by specifying a list of table names
in the FROM clause of the SQL statement

 MySQL provides an alternative syntax using the JOIN


keyword

 JOIN keyword allows several different types of table


joins to be performed
Inner Join

 Inner join or equijoin uses a condition to specify a


relationship between tables in which a column in one
table is equal to another column in the other table

 mysql> SELECT fields FROM table1 INNER JOIN table2


ON table1.field1 = table2.field2

 If there are rows in the second table that do not have


matches in the first table, those rows will NOT be listed
Cross Join

 If no relationship between joined tables is given in


the WHERE clause, a Cartesian product or Cross Join
is produced

 The ON keyword is not required

 mysql> SELECT * FROM table1 CROSS JOIN table2


Outer Join

 Most joins return rows based on pairs of records from


the two joined tables according to a given
relationship

 The Outer Join is different:

 All the rows from on table are returned, regardless of


whether the relationship condition finds a matching
row in the second table
Left Join

 The LEFT JOIN keyword returns all rows from the left
table (first table), even if there are no matches in
the right table (second table)

 mysql> SELECT fields FROM table1 LEFT JOIN table2


ON table1.field1 = table2.field2

 In some databases LEFT JOIN is called LEFT OUTER


JOIN
Right Join

 The RIGHT JOIN keyword Return all rows from the


right table (table2), even if there are no matches in
the left table (table1)

 mysql> SELECT fields FROM table1 RIGHT JOIN table2


ON table1.field1 = table2.field2

 In some databases RIGHT JOIN is called RIGHT


OUTER JOIN
Combining Queries

 The technique of combining two or more independent queries into


a single data set is known as a UNION or Compound query

 mysql> SELECT fields FROM table1 UNION SELECT fields FROM table2

 Consider these limitations:


 Each SELECT statement must have the same number of
columns
 The columns must also have similar data types
 the columns in each SELECT statement must be in the same
order
UNION ALL

 The UNION operator selects only distinct values by


default

 To allow duplicate values, use UNION ALL

 mysql> SELECT fields FROM table1 UNION ALL SELECT


fields FROM table2
Numeric Operators

 Arithmetic Operators:
 +, -, *, /
 DIV, MOD (%)
 Precedence: multiplication and division have higher priority
than addition and subtraction

 NULL Values:
 NULL is no value, it is not the same as zero
 Performing any kind of arithmetic operation which one of
operand is NULL, result always NULL
 Use IS NULL or IS NOT NULL, comparing column = NULL does not
work
MySQL Functions

 A function is a MySQL command used in an SQL


statement that takes one or more arguments and
returns a value based on the values supplied

 Functions are not case sensitive


 Arguments always separate with comma
enclosed by parenthesis
 If a function does not require arguments, the
parenthesis must still be given for instance
 Aggregate functions, Scalar functions
Numeric Functions

 RAND()

 To generate a random number


 You can shuffle the result of a query by using this function

 ROUND(number, decimal)

 Rounds a value up or down to the nearest integer

 CEILING(number)

 Rounds a decimal number up

 FLOOR(number)

 Rounds a decimal number down


Numeric Functions

 TRUNCATE(number, decimal)
 It does not round the number, but simply
removes from it decimal places

 POW(a, b)
 Raises a to b

 SQRT(number)
 It calculate the square root of a number
Numeric Functions

 LOG(base, number)
 It calculate the logarithm of a number based on first
argument

 EXP(number)
 It raises natural log base (e) to the power given in
argument

 PI()
 Shows the value of pi number
Numeric Functions

 SIN(value)

 Calculate the sine of value

 COS(value)

 Calculate the cosine value

 TAN(value)

 Calculate the tangent value

 DEGREES()

 Convert degree to radian

 RADIANS()

 Convert radians to degree


Conditional Functions

 IF()
 mysql> SELECT fields, IF(condition, true, false) FROM table

 The CASE Statement:

 mysql> SELECT fields,


CASE WHEN condition1 THEN value1
WHEN condition2 THEN value2
ELSE value3 END as fieldname
FROM tablename
Conditional Functions

 IFNULL(value1,value2)
 Provides a shortcut when you expect to see NULL
values
 If the first argument is null, the second argument is
returned, otherwise the first argument will returned

 NULLIF(value1,value2)
 Use NULLIF to return NULL when two values are the
same. If the two expressions passed to NULLIF are
the same, the result is NULL, otherwise the first
argument will returned
String Operators

 Comparison Operators:

 IN(‘value1’, ‘value2’)
 LIKE pattern (use % and _ to build a pattern)
 BETWEEN ‘char1’ AND ‘char2’

 BINARY Ordering:
 For case sensitive ordering, user ORDR BY BINARY

 Type Conversion: ‘100’, ‘100 apples’, USD 100’, ‘4*2’


String Functions

 CONCAT(text1, text2)
 Joins two or more strings

 CONCAT_WS(separator, text1, text2)


 Joins two or more strings with separator

 LTRIM(string)
 Removes space characters from the left

 RTRIM(string)
 Removes space characters from the right
String Functions

 TRIM(direction ‘symbol’ FROM string)


 It enables you to trim other character from both
ends of a string (use LEADING, TRAILING, BOTH)

 RPAD(string, length, symbol)


 Pad a string to a fixed length by inserting character
on the right

 LPAD(string, length, symbol)


 Pad a string to a fixed length by inserting character
on the left
String Functions

 LOCATE(keyword, string)
 Returns the position of a substring within a string

 LENGTH(string)
 Returns the total number of characters in a strings

 REPLACE(string, old char, new char)


 Replace one substring with another within a string
String Functions

 SUBSTRING()
 Returns only a fixed portion of a string
 SUBSTRING(string, start, length)

 SUBSTRING_INDEX()
 Returns a part from a single string
 SUBSTRING_INDEX(string, delimiter, part)
String Functions

 UPPER()
 Convert string to uppercase

 LOWER()
 Convert string to lowercase

 Note: using NULL in an expression always causes the


result to be NULL!
 Remember: NULL is not equal to an empty string!
Date Operators

 mysql> SELECT ‘2010-06-01’ + 10


 mysql> SELECT 20100601 + 10

 Is it unpredictable? Use INTERVAL keyword:

 mysql> SELECT ‘2010-06-01’ + INTERVAL 10 DAY


 mysql> SELECT ‘2010-06-01’ + INTERVAL 1 MONTH

 Note: MySQL requires the unit keyword to be singular,


regardless of English grammar rules
Date Operators

 INTERVAL Unit Keyword:

 MICROSECOND
 SECOND
 MINUTE
 HOUR
 DAY
 WEEK
 MONTH
 QUARTER
 YEAR
Date Functions

 CURDATE()
 Returns the current date

 CURTIME()
 Returns the current time

 NOW()
 Returns the current date and time as a single
value
Date Functions

 DATE_FORMAT(date, format)

 Date Format Characters:

 %a – Abbreviated weekday name


 %b – Abbreviated month name
 %c – Month number
 %D – Day of the month with ordinal suffix
 %d – Day of the month
 %j – three digits day of the year
Date Functions

 Date Format Characters:

 %M – Month name
 %m – Two digits month number
 %U – Week number
 %u – Week number
 %W – Weekday name
 %Y – Four digits year
 %y – Two digits year
Date Functions

 Time Format Characters:

 %H – Two digits hour on 24 hour clock


 %h – Hour on 12 hour clock
 %i – Two digits minutes
 %l – Hour on 12 Hour no leading zero
 %p – AM or PM
 %r – Time on 12 hour clock
 %s – Two digits second
 %T – Time on 24 hour clock
Date Functions

 EXTRACT(what FROM date)


 Returns part of the date

 DATEDIFF(date, date)
 Returns the difference between two dates

 TIMEDIFF(time, time)
 Returns the difference between two times
Aggregate Functions

 1- COUNT()
 Counts values in a query
 It never counts columns with null values

 2- SUM()
 Computes a total from the data in a specified column

 3- AVG()
 Compute an average of the data in a specified
column
Aggregate Functions

 4- MIN()
 Return the smallest value from a column

 5- MAX()
 Return the greatest value from a column

 Note: Aggregate functions totally ignore columns


having NULL value
Grouping Data

 Grouping is a SQL feature that enables you to


produce summary data on groups of rows in the
result set

 mysql> SELECT fields FROM tablename GROUP BY


fieldname

 Note: if you do not supply an ORDER BY clause, the


query will be ordered on the columns specified in
the GROUP BY clause
Filtering Summary Data

 You cannot reference a column produced by an


aggregate function in a WHERE clause. Instead, you
must use HAVING clause

 mysql> SELECT fields FROM tablename GROUP BY


fieldname HAVING aggregate function operator
value
Part 5:
Managing User
Access
MySQL Authentication

 MySQL has a multiuser access control system that can


allow or prevent each user from having access to a
particular database or individual tables.

 You can even restrict the types of operations the user is


able to perform on a table.

 Web Access: You will usually have only a single user


account through which all the connections from the
web scripts are performed. Your application will handle
any additional user authentication that is required in
the web browser.
The mysql Database

 Users can have Individual Privileges like: ALTER,


CREATE, DROP, INSERT, SELECT, UPDATE and etc.

 Privileges data for each user stored in “mysql”


database which only a MySQL super user can have
access to it.

 General privileges stored in “user” table while


individual table privileges are stored in the
“tables_priv“ table.
Changing Privileges

 Although it is possible to query and update the


privileges tables directly, it is much easier and
secure to use the GRANT and REVOKE commands.

 Furthermore, changes made to the privileges tables


do not take effect until you issue the FLUSH
PRIVILEGES command
Creating New User

 mysql> CREATE USER username@host IDENTIFIED BY


‘password’

 mysql> SET PASSWORD FOR username@host =


PASSWORD(‘password’)
 Only a Super user can change other user’s
passwords

 mysql> SET PASSWORD = PASSWORD(‘password’)


Granting Privileges

 mysql> GRANT privilege1, privilege2, privilege n ON


dbname.tablename TO user@host

 Use ALL PRIVILEGES if you want!

 mysql> GRANT privilege1, privilege2, privilege n ON


dbname.tablename TO user@host WITH GRANT
OPTION
Revoking Privileges

 mysql> REVOKE privilege1, privilege2, privilege n ON


dbname.tablename FROM user@host

 mysql> REVOKE ALL PRIVILEGES ON


dbname.tablename FROM user@host
Using Wildcards

 You can grant or revoke privileges to|from


username that match wildcard criteria by using the
% and _ wildcard characters in the username

 % for multiple character


 _ for single character

 Note: Remember to enclosed username in double


quotes if it contains a wildcard character.
Deleting a User

 mysql> DROP USER user@host

 mysql> FLUSH PRIVILEGES

 mysql> SHOW GRANTS FOR user@host

 mysql> SHOW GRANTS


Part 6:
New Feature in
MySQL 5.0
Views

 A view is a pseudo table or virtual table

 You can reference a view just like you reference a real table in
a select statement

 Views are a tool of convenience

 Views are not tables! Or just a copy of a table!

 You can also use some views with insert, update, delete
statement

 The name of a view must be unique across both views and


tables
Creating a View

 mysql> CREATE VIEW viewname AS SELECT fields FROM


tablename WHERE somefield = somevalue

 Because views behave just like tables, the SHOW


TABLES command will show all your views as well as
your table:

 mysql> SHOW TABLES

 mysql> SHOW CREATE VIEW viewname


Updating Views

 Some views are updatable, but not always

 So we have updatable views and non updatable views

 A view cannot be updated if its query contains any of the following


features:

 The DISTINCT keyword


 A GROUP BY clause
 Any aggregate function
 Derived column
Inserting into Views

 You cannot insert into two tables simultaneously

 You can insert into a view if it have an inner join

 You can insert into a view with inner joined tables if all
the columns you insert into are from the same table

 You cannot insert into any view that uses the UNION or
UNION ALL operator
Altering & Dropping
Views

 mysql> ALTER VIEW viewname AS SELECT fields FROM


tablename WHERE somefield = somevalue

 mysql> DROP VIEW viewname


Stored Routines

 Stored procedure is a series of SQL statements


stored in a MySQL database

 For a frequently executed series of commands, this


is a time-saving feature

 Stored function is a stored routine that can return a


value to SQL
Creating Stored
Procedure

 mysql> CREATE PROCEDURE name() statement AS


fieldname

 To execute a procedure, use CALL command:

 mysql> CALL procedureName()


Powerful Stored
Procedures
 The real power of stored routines are in their capability to
execute many different SQL commands in a single procedure
call
 mysql> CREATE PROCEDURE name (parameter DataType)
Begin
Query 1
Query 2
Query n
END
* Note: use another delimiter instead of ;
Creating Stored Function

 Procedures do not return a value, to do that, you


must use a function
 functions are called from SQL statements without
CALL keyword
 It is possible for a function and a procedure to share
a same name but using unique name for each is
recommanded!
 mysql> CREATE FUNCTION name(parameter)
RETURNS datatype RETURN statement
Privileges and Stored
Routines

 A user must have the EXECUTE privilege to execute


a stored procedure

 Creator of a stored routine has this privilege


automatically

 mysql> GRANT EXECUTE ON FUNCTION|PROCEDURE


name TO user@domain
Dropping Stored Routines

 mysql> DROP PROCEDURE procedureName

 mysql> DROP FUNCTION functionName

 Note: Also you can use IF EXISTS statement with


DROP command to avoid probable errors
Triggers

 A trigger is a stored database object that contains a


series of SQL commands, set to activate
automatically when certain events take place
 Each trigger is associated with a table
 Triggers will automatically fire when an INSERT,
UPDATE or DELETE command takes place on the
named table

 * What about REPLACE statement?


Creating a Trigger

 mysql> CREATE TRIGGER triggername Timing Event


ON tablename FOR EACH ROW BEGIN statements
END

 Timing: BEFORE, AFTER


 Event: INSERT, UPDATE, DELETE

 Note: BEGIN and END keywords are necessary if the


trigger has more than one statement
Trigger Useful Keywords

 When a trigger is activated, the stored code can


access data record that caused the trigger event to
occur

 Use OLD keyword to reference deleted values and


the previous values from an updated row

 Use NEW to reference the new values in the


database when using UPDATE or INSERT
Dropping Triggers

 mysql> DROP TRIGGER triggerName

 mysql> SHOW TRIGGERS

 mysql> SHOW TRIGGERS LIKE ‘tablename’

 Note: Only a super user has privilege to use the CREATE


TRIGGER command, there is no separate privilege exist
to allow users to create triggers
Part 7:
Interfacing with
MySQL
Introduction to PHP

 PHP stands for PHP: Hypertext Preprocessor

 PHP is a server-side scripting language

 PHP supports many databases (MySQL, Informix,


Oracle, Sybase, Solid, PostgreSQL, Generic ODBC,
etc.)

 PHP is an open source software


Why using PHP?

 PHP combined with MySQL are cross-platform (you can


develop in Windows and serve on a Linux platform)
 PHP runs on different platforms (Windows, Linux, Unix,
etc.)
 PHP is compatible with almost all servers used today
(Apache, IIS, etc.)
 PHP is FREE to download from the official PHP
resource: www.php.net
 PHP is easy to learn and runs efficiently on the server
side
PHP Basic

 PHP Syntax (declaration, case sensitive, terminator)

 PHP Variable (concept, declaration, initialization)

 PHP Array (concept, types, declaration, index, print_r)

 PHP Function (concept, declaration, parameter, return)

 IF Condition (syntax, true – false)


Using MySQL with PHP

 mysql_connect(server,username,password)

 mysql_select_db(dbname)

 mysql_query(query, connection)

 mysql_num_rows(recordset)

 mysql_fetch_assoc(recordset)
End of

Database
Implementation

You might also like