SlideShare a Scribd company logo
1 of 48
Unit 2
Introduction to MySQL
Naming Database Elements
Rules:
• Letters, numbers, underscore
• No keywords
• Case-sensitive
• <=64 characters
• unique
To name a database element:
• Determine database’s name
• Determine table’s name
• Determine the column names inside the table.
Choose the column type
• Text, number, date/time type
• Most appropriate type
• Set maximum length
• Char
• Varchar
Column Properties
• Index
• Key
• 2 types of keys: primary & foreign
• 3 rules:
Must have a value
Never change
Unique
Key Constraint
• Auto increment
• Not null
• Default
• Timestamp
• Enum
• Unsigned
• Zerofill
Rules for defining column
• Identify primary key
• Identify column-not null
• Identify column-unsigned
• Default value
• Confirm final column definition
Accessing MySQL
• Client applications: mysql client & phpMyAdmin
• Mysql client:
Command-line prompt
To start: type ‘mysql’
Xampp-C:xamppmysqlbinmysql
Mamp-/Applications/MAMP/Library/bin/mysql
To establish the connection: mysql -u username -h hostname –p
Steps to use mysql client: access, invoke, enter password, select DB, quit
mysql, quit terminal.
Accessing MySQL
• phpMyAdmin:
Best and most popular
Easy to use
Access: http://localhost/phpMyAdmin
Steps: access, select DB, select table, perform task, execute SQL commands
Introduction to SQL
Creating Database and Tables
• To create Database:
CREATE DATABASE databasename;
Eg: CREATE DATABASE sitename;
USE sitename;
• To create table:
CREATE TABLE tablename (
column1name description,
column2name description
…);
Creating table
• Eg:
CREATE TABLE users (
user_id MEDIUMINT UNSIGNED NOT NULL
AUTO_INCREMENT,
first_name VARCHAR(20) NOT NULL,
last_name VARCHAR(40) NOT NULL,
email VARCHAR(60) NOT NULL,
pass CHAR(40) NOT NULL,
registration_date DATETIME NOT NULL,
PRIMARY KEY (user_id)
);
Viewing table
• SHOW TABLES;
• SHOW COLUMNS FROM tablename;
(or)
DESCRIBE tablename;
Viewing table
Inserting record
Two methods:
• INSERT INTO tablename (column1, column2…) VALUES (value1,
value2 …);
INSERT INTO tablename (column4, column8) VALUES (valueX, valueY);
• INSERT INTO tablename VALUES (value1, NULL, value2, value3, …);
• Insert multiple row at a time:
INSERT INTO tablename (column1, column4) VALUES (valueA, valueB),
(valueC, valueD),(valueE, valueF);
Example
• INSERT INTO users (first _ name, last _ name, email, pass,
registration_date) VALUES ('Larry', 'Ullman', 'email@example.com’,
SHA1('mypass’), NOW( ));
Two MySQL functions
• SHA1()
to encrypt data.
• NOW()
return current date and time.
Rules
• Numeric value shouldn’t be quoted.
• String values must always be quoted.
• Date and time values must always be quoted.
• Functions cannot be quoted.
• The word NULL must not be quoted.
Selecting data
• Syntax: SELECT which_columns FROM which_table;
• SELECT * FROM tablename;
• SELECT column1, column3 FROM tablename;
• SELECT NOW();
• Can select the order & can display multiple times.
Example
Example
Using Conditionals
Syntax: SELECT which_columns FROM which_table WHERE condition(s);
Example:
• SELECT name FROM people WHERE birth_date = '2011-01-26’;
• SELECT * FROM items WHERE (price BETWEEN 10.00 AND 20.00) AND
(quantity > 0)
SELECT * FROM cities WHERE (zip _code = 90210) OR (zip _code =90211);
• SELECT * FROM cities WHERE zip_code IN (90210, 90211)
MySQL Operators
Example
Example
Example
SELECT first_name, last_name FROM
users WHERE user_id
NOT BETWEEN 10 and 20;
SELECT first_name, last_name FROM
users WHERE user_id NOT IN
(10, 11, 12, 13, 14, 15, 16, 17, 18,
➝19, 20);
LIKE & NOT LIKE
• SELECT * FROM users WHERE last_name = 'Simpson’;
• SELECT * FROM users WHERE last_name LIKE 'Smith%’;
Eg: SELECT * FROM users WHERE last_name LIKE 'Bank%';
Example
• SELECT first_name, last_name FROM users WHERE email NOT LIKE
'%@authors.com’;
• SELECT * FROM users WHERE last_name LIKE ' _smith%'
Sorting Query
• Syntax :
1.SELECT * FROM tablename ORDER BY column;
2.SELECT * FROM tablename ORDER BY column DESC;
3.SELECT * FROM tablename WHERE conditions ORDER BY column;
4. SELECT * FROM tablename ORDER BY column1, column2
• Eg: SELECT * FROM orders ORDER BY total;
Example
Example
Limiting Query results
• Syntax:
1. SELECT * FROM tablename LIMIT x;
2. SELECT * FROM tablename LIMIT x, y;
3. SELECT which_columns FROM tablename WHERE conditions ORDER
BY column LIMIT x;
Eg:
SELECT * FROM tablename LIMIT 3;
SELECT * FROM tablename LIMIT 10, 10;
Example
SELECT first_name, last_name
FROM users ORDER BY
registration_date DESC LIMIT 5;
SELECT first_name, last_name
FROM users ORDER BY
registration_date ASC LIMIT 1, 1;
Updating data
• Syntax:
1. UPDATE tablename SET column=value;
2. UPDATE tablename SET column1=valueA, column5=valueB;
3. UPDATE tablename SET column2=value WHERE column5=value;
Example
SELECT user_id FROM users
WHERE first_name = 'Michael'
AND last_name='Chabon';
UPDATE users
SET email='mike@authors.com'
WHERE user_id = 18;
Deleting Data
• Syntax:
1. DELETE FROM tablename;
2. DELETE FROM tablename WHERE condition;
3. TRUNCATE TABLE tablename;
4. DROP TABLE tablename;
5. DROP DATABASE databasename;
Aliases
• SELECT registration_date AS reg FROM users;
• SELECT first_name AS name FROM users WHERE name='Sam’;
Using functions
• SELECT FUNCTION(column) FROM tablename;
• SELECT *, FUNCTION(column) FROM tablename;
• SELECT column1, FUNCTION(column2), column3 FROM tablename;
Text functions
Example
• SELECT CONCAT(t1, t2) FROM tablename;
• SELECT CONCAT(last_name, ', ‘, first_name) FROM users;
• SELECT CONCAT(last_name, ', ', first_name) AS Name FROM users
ORDER BY Name;
• SELECT LENGTH(last_name) AS L, last_name FROM users ORDER BY L
DESC LIMIT 1;
• SELECT CONCAT_WS(' ', first, middle, last) AS Name FROM tablename;
Numeric function
Example
• SELECT * FROM tablename ORDER BY RAND( );
• SELECT CONCAT('$', FORMAT(5639.6, 2)) AS cost;
• SELECT email FROM users ORDER BY RAND( ) LIMIT 1;
• SELECT MOD(9,2) == SELECT 9%2
Date and time function
Example
• SELECT DATE(registration_date) AS Date FROM users ORDER BY
registration_date DESC LIMIT 1;
• SELECT DAYNAME(registration_date) AS Weekday FROM users ORDER
BY registration_date ASC LIMIT 1;
• SELECT CURDATE( ), CURTIME( );
• SELECT LAST_DAY(CURDATE( )), MONTHNAME(CURDATE( ));
• ADDDATE( ), SUBDATE( ), ADDTIME( ), SUBTIME( ), and DATEDIFF( ).
Formatting the date and time
Example
• Time (11:07:45 AM)
= TIME_FORMAT(the_date, '%r')
• Time without seconds (11:07 AM)
= TIME_FORMAT(the_date, '%l:%i %p')
• Date (April 20th, 1996)
=DATE_FORMAT(the_date, '%M %D, %Y’)
• SELECT DATE_FORMAT(NOW( ),'% M % e, % Y %l:%i’);
• SELECT TIME_FORMAT(CURTIME( ),'% T’);
• SELECT email, DATE_FORMAT (registration_date, '%a %b %e %Y’) AS Date
FROM users
• ORDER BY registration_date DESC LIMIT 5;

More Related Content

What's hot

What's hot (17)

Web technology html5 php_mysql
Web technology html5 php_mysqlWeb technology html5 php_mysql
Web technology html5 php_mysql
 
PHP Variables and scopes
PHP Variables and scopesPHP Variables and scopes
PHP Variables and scopes
 
Some OOP paradigms & SOLID
Some OOP paradigms & SOLIDSome OOP paradigms & SOLID
Some OOP paradigms & SOLID
 
PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & Arrays
 
Php variables
Php variablesPhp variables
Php variables
 
Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Алексей Секрето...
Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Алексей Секрето...Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Алексей Секрето...
Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Алексей Секрето...
 
How to write code you won't hate tomorrow
How to write code you won't hate tomorrowHow to write code you won't hate tomorrow
How to write code you won't hate tomorrow
 
Cursors
CursorsCursors
Cursors
 
5java Io
5java Io5java Io
5java Io
 
Table through php
Table through phpTable through php
Table through php
 
Development Approach
Development ApproachDevelopment Approach
Development Approach
 
Les10
Les10Les10
Les10
 
Web 4 | Core JavaScript
Web 4 | Core JavaScriptWeb 4 | Core JavaScript
Web 4 | Core JavaScript
 
Rails 3 hints
Rails 3 hintsRails 3 hints
Rails 3 hints
 
Web 8 | Introduction to PHP
Web 8 | Introduction to PHPWeb 8 | Introduction to PHP
Web 8 | Introduction to PHP
 
Web 9 | OOP in PHP
Web 9 | OOP in PHPWeb 9 | OOP in PHP
Web 9 | OOP in PHP
 
Stored procedure with cursor
Stored procedure with cursorStored procedure with cursor
Stored procedure with cursor
 

Similar to Introduction to MySQL in PHP

Farheen abdul hameed ip project (MY SQL);
Farheen abdul hameed ip project (MY SQL);Farheen abdul hameed ip project (MY SQL);
Farheen abdul hameed ip project (MY SQL);
abdul talha
 
e computer notes - Creating and managing tables
e computer notes -  Creating and managing tablese computer notes -  Creating and managing tables
e computer notes - Creating and managing tables
ecomputernotes
 
Using ddl statements to create and manage tables
Using ddl statements to create and manage tablesUsing ddl statements to create and manage tables
Using ddl statements to create and manage tables
Syed Zaid Irshad
 
MySQL Database System Hiep Dinh
MySQL Database System Hiep DinhMySQL Database System Hiep Dinh
MySQL Database System Hiep Dinh
webhostingguy
 

Similar to Introduction to MySQL in PHP (20)

Database
Database Database
Database
 
Dictionary.coumns is your friend while appending or moving data
Dictionary.coumns is your friend while appending or moving dataDictionary.coumns is your friend while appending or moving data
Dictionary.coumns is your friend while appending or moving data
 
Tk2323 lecture 7 sql
Tk2323 lecture 7   sql Tk2323 lecture 7   sql
Tk2323 lecture 7 sql
 
Structured Query Language(SQL)
Structured Query Language(SQL)Structured Query Language(SQL)
Structured Query Language(SQL)
 
Farheen abdul hameed ip project (MY SQL);
Farheen abdul hameed ip project (MY SQL);Farheen abdul hameed ip project (MY SQL);
Farheen abdul hameed ip project (MY SQL);
 
e computer notes - Creating and managing tables
e computer notes -  Creating and managing tablese computer notes -  Creating and managing tables
e computer notes - Creating and managing tables
 
Using ddl statements to create and manage tables
Using ddl statements to create and manage tablesUsing ddl statements to create and manage tables
Using ddl statements to create and manage tables
 
DataStructures.pptx
DataStructures.pptxDataStructures.pptx
DataStructures.pptx
 
Data Base Management System Lecture 10.pdf
Data Base Management System Lecture 10.pdfData Base Management System Lecture 10.pdf
Data Base Management System Lecture 10.pdf
 
Cassandra Community Webinar | Become a Super Modeler
Cassandra Community Webinar | Become a Super ModelerCassandra Community Webinar | Become a Super Modeler
Cassandra Community Webinar | Become a Super Modeler
 
Mysql
MysqlMysql
Mysql
 
MySQL Database System Hiep Dinh
MySQL Database System Hiep DinhMySQL Database System Hiep Dinh
MySQL Database System Hiep Dinh
 
mysqlHiep.ppt
mysqlHiep.pptmysqlHiep.ppt
mysqlHiep.ppt
 
38c
38c38c
38c
 
SQL
SQLSQL
SQL
 
DBMS.pptx
DBMS.pptxDBMS.pptx
DBMS.pptx
 
Unit - II.pptx
Unit - II.pptxUnit - II.pptx
Unit - II.pptx
 
2..basic queries.pptx
2..basic queries.pptx2..basic queries.pptx
2..basic queries.pptx
 
Ms sql-server
Ms sql-serverMs sql-server
Ms sql-server
 
Introduction to sql_02
Introduction to sql_02Introduction to sql_02
Introduction to sql_02
 

More from hamsa nandhini

More from hamsa nandhini (17)

SOA - Unit 5 - SOA and Business Process Management
SOA - Unit   5 - SOA and Business Process ManagementSOA - Unit   5 - SOA and Business Process Management
SOA - Unit 5 - SOA and Business Process Management
 
SOA - Unit 4 - SOA & Web Services for integration and Multi-Channel access
SOA - Unit   4 - SOA & Web Services for integration and Multi-Channel accessSOA - Unit   4 - SOA & Web Services for integration and Multi-Channel access
SOA - Unit 4 - SOA & Web Services for integration and Multi-Channel access
 
SOA - Unit 3 - SOA and Web Services
SOA - Unit   3 - SOA and Web ServicesSOA - Unit   3 - SOA and Web Services
SOA - Unit 3 - SOA and Web Services
 
SOA - Unit 2 - Service Oriented Architecture
SOA - Unit   2 - Service Oriented ArchitectureSOA - Unit   2 - Service Oriented Architecture
SOA - Unit 2 - Service Oriented Architecture
 
SOA - Unit 1 - Introduction to SOA with Web Services
SOA - Unit   1 - Introduction to SOA with Web ServicesSOA - Unit   1 - Introduction to SOA with Web Services
SOA - Unit 1 - Introduction to SOA with Web Services
 
NP - Unit 5 - Bootstrap, Autoconfigurion and BGP
NP - Unit 5 - Bootstrap, Autoconfigurion and BGPNP - Unit 5 - Bootstrap, Autoconfigurion and BGP
NP - Unit 5 - Bootstrap, Autoconfigurion and BGP
 
NP - Unit 4 - Routing - RIP, OSPF and Internet Multicasting
NP - Unit 4 - Routing - RIP, OSPF and Internet MulticastingNP - Unit 4 - Routing - RIP, OSPF and Internet Multicasting
NP - Unit 4 - Routing - RIP, OSPF and Internet Multicasting
 
NP - Unit 3 - Forwarding Datagram and ICMP
NP - Unit 3 - Forwarding Datagram and ICMPNP - Unit 3 - Forwarding Datagram and ICMP
NP - Unit 3 - Forwarding Datagram and ICMP
 
NP - Unit 2 - Internet Addressing, ARP and RARP
NP - Unit 2 - Internet Addressing, ARP and RARP NP - Unit 2 - Internet Addressing, ARP and RARP
NP - Unit 2 - Internet Addressing, ARP and RARP
 
Unit 1
Unit 1Unit 1
Unit 1
 
Web application, cookies and sessions
Web application, cookies and sessionsWeb application, cookies and sessions
Web application, cookies and sessions
 
PHP with MySQL
PHP with MySQLPHP with MySQL
PHP with MySQL
 
XML Security
XML SecurityXML Security
XML Security
 
SOAP and Web services
SOAP and Web servicesSOAP and Web services
SOAP and Web services
 
XML Technologies
XML TechnologiesXML Technologies
XML Technologies
 
XML DTD and Schema
XML DTD and SchemaXML DTD and Schema
XML DTD and Schema
 
fundamentals of XML
fundamentals of XMLfundamentals of XML
fundamentals of XML
 

Recently uploaded

Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Christo Ananth
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
ankushspencer015
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Dr.Costas Sachpazis
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
Tonystark477637
 

Recently uploaded (20)

Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTINGMANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 

Introduction to MySQL in PHP

  • 2. Naming Database Elements Rules: • Letters, numbers, underscore • No keywords • Case-sensitive • <=64 characters • unique
  • 3. To name a database element: • Determine database’s name • Determine table’s name • Determine the column names inside the table.
  • 4. Choose the column type • Text, number, date/time type • Most appropriate type • Set maximum length
  • 5.
  • 7. Column Properties • Index • Key • 2 types of keys: primary & foreign • 3 rules: Must have a value Never change Unique
  • 8. Key Constraint • Auto increment • Not null • Default • Timestamp • Enum • Unsigned • Zerofill
  • 9. Rules for defining column • Identify primary key • Identify column-not null • Identify column-unsigned • Default value • Confirm final column definition
  • 10. Accessing MySQL • Client applications: mysql client & phpMyAdmin • Mysql client: Command-line prompt To start: type ‘mysql’ Xampp-C:xamppmysqlbinmysql Mamp-/Applications/MAMP/Library/bin/mysql To establish the connection: mysql -u username -h hostname –p Steps to use mysql client: access, invoke, enter password, select DB, quit mysql, quit terminal.
  • 11. Accessing MySQL • phpMyAdmin: Best and most popular Easy to use Access: http://localhost/phpMyAdmin Steps: access, select DB, select table, perform task, execute SQL commands
  • 13. Creating Database and Tables • To create Database: CREATE DATABASE databasename; Eg: CREATE DATABASE sitename; USE sitename; • To create table: CREATE TABLE tablename ( column1name description, column2name description …);
  • 14. Creating table • Eg: CREATE TABLE users ( user_id MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT, first_name VARCHAR(20) NOT NULL, last_name VARCHAR(40) NOT NULL, email VARCHAR(60) NOT NULL, pass CHAR(40) NOT NULL, registration_date DATETIME NOT NULL, PRIMARY KEY (user_id) );
  • 15. Viewing table • SHOW TABLES; • SHOW COLUMNS FROM tablename; (or) DESCRIBE tablename;
  • 17. Inserting record Two methods: • INSERT INTO tablename (column1, column2…) VALUES (value1, value2 …); INSERT INTO tablename (column4, column8) VALUES (valueX, valueY); • INSERT INTO tablename VALUES (value1, NULL, value2, value3, …); • Insert multiple row at a time: INSERT INTO tablename (column1, column4) VALUES (valueA, valueB), (valueC, valueD),(valueE, valueF);
  • 18. Example • INSERT INTO users (first _ name, last _ name, email, pass, registration_date) VALUES ('Larry', 'Ullman', 'email@example.com’, SHA1('mypass’), NOW( ));
  • 19. Two MySQL functions • SHA1() to encrypt data. • NOW() return current date and time.
  • 20. Rules • Numeric value shouldn’t be quoted. • String values must always be quoted. • Date and time values must always be quoted. • Functions cannot be quoted. • The word NULL must not be quoted.
  • 21. Selecting data • Syntax: SELECT which_columns FROM which_table; • SELECT * FROM tablename; • SELECT column1, column3 FROM tablename; • SELECT NOW(); • Can select the order & can display multiple times.
  • 24. Using Conditionals Syntax: SELECT which_columns FROM which_table WHERE condition(s); Example: • SELECT name FROM people WHERE birth_date = '2011-01-26’; • SELECT * FROM items WHERE (price BETWEEN 10.00 AND 20.00) AND (quantity > 0) SELECT * FROM cities WHERE (zip _code = 90210) OR (zip _code =90211); • SELECT * FROM cities WHERE zip_code IN (90210, 90211)
  • 28. Example SELECT first_name, last_name FROM users WHERE user_id NOT BETWEEN 10 and 20; SELECT first_name, last_name FROM users WHERE user_id NOT IN (10, 11, 12, 13, 14, 15, 16, 17, 18, ➝19, 20);
  • 29. LIKE & NOT LIKE • SELECT * FROM users WHERE last_name = 'Simpson’; • SELECT * FROM users WHERE last_name LIKE 'Smith%’; Eg: SELECT * FROM users WHERE last_name LIKE 'Bank%';
  • 30. Example • SELECT first_name, last_name FROM users WHERE email NOT LIKE '%@authors.com’; • SELECT * FROM users WHERE last_name LIKE ' _smith%'
  • 31. Sorting Query • Syntax : 1.SELECT * FROM tablename ORDER BY column; 2.SELECT * FROM tablename ORDER BY column DESC; 3.SELECT * FROM tablename WHERE conditions ORDER BY column; 4. SELECT * FROM tablename ORDER BY column1, column2 • Eg: SELECT * FROM orders ORDER BY total;
  • 34. Limiting Query results • Syntax: 1. SELECT * FROM tablename LIMIT x; 2. SELECT * FROM tablename LIMIT x, y; 3. SELECT which_columns FROM tablename WHERE conditions ORDER BY column LIMIT x; Eg: SELECT * FROM tablename LIMIT 3; SELECT * FROM tablename LIMIT 10, 10;
  • 35. Example SELECT first_name, last_name FROM users ORDER BY registration_date DESC LIMIT 5; SELECT first_name, last_name FROM users ORDER BY registration_date ASC LIMIT 1, 1;
  • 36. Updating data • Syntax: 1. UPDATE tablename SET column=value; 2. UPDATE tablename SET column1=valueA, column5=valueB; 3. UPDATE tablename SET column2=value WHERE column5=value;
  • 37. Example SELECT user_id FROM users WHERE first_name = 'Michael' AND last_name='Chabon'; UPDATE users SET email='mike@authors.com' WHERE user_id = 18;
  • 38. Deleting Data • Syntax: 1. DELETE FROM tablename; 2. DELETE FROM tablename WHERE condition; 3. TRUNCATE TABLE tablename; 4. DROP TABLE tablename; 5. DROP DATABASE databasename;
  • 39. Aliases • SELECT registration_date AS reg FROM users; • SELECT first_name AS name FROM users WHERE name='Sam’;
  • 40. Using functions • SELECT FUNCTION(column) FROM tablename; • SELECT *, FUNCTION(column) FROM tablename; • SELECT column1, FUNCTION(column2), column3 FROM tablename;
  • 42. Example • SELECT CONCAT(t1, t2) FROM tablename; • SELECT CONCAT(last_name, ', ‘, first_name) FROM users; • SELECT CONCAT(last_name, ', ', first_name) AS Name FROM users ORDER BY Name; • SELECT LENGTH(last_name) AS L, last_name FROM users ORDER BY L DESC LIMIT 1; • SELECT CONCAT_WS(' ', first, middle, last) AS Name FROM tablename;
  • 44. Example • SELECT * FROM tablename ORDER BY RAND( ); • SELECT CONCAT('$', FORMAT(5639.6, 2)) AS cost; • SELECT email FROM users ORDER BY RAND( ) LIMIT 1; • SELECT MOD(9,2) == SELECT 9%2
  • 45. Date and time function
  • 46. Example • SELECT DATE(registration_date) AS Date FROM users ORDER BY registration_date DESC LIMIT 1; • SELECT DAYNAME(registration_date) AS Weekday FROM users ORDER BY registration_date ASC LIMIT 1; • SELECT CURDATE( ), CURTIME( ); • SELECT LAST_DAY(CURDATE( )), MONTHNAME(CURDATE( )); • ADDDATE( ), SUBDATE( ), ADDTIME( ), SUBTIME( ), and DATEDIFF( ).
  • 48. Example • Time (11:07:45 AM) = TIME_FORMAT(the_date, '%r') • Time without seconds (11:07 AM) = TIME_FORMAT(the_date, '%l:%i %p') • Date (April 20th, 1996) =DATE_FORMAT(the_date, '%M %D, %Y’) • SELECT DATE_FORMAT(NOW( ),'% M % e, % Y %l:%i’); • SELECT TIME_FORMAT(CURTIME( ),'% T’); • SELECT email, DATE_FORMAT (registration_date, '%a %b %e %Y’) AS Date FROM users • ORDER BY registration_date DESC LIMIT 5;