SlideShare a Scribd company logo
Database Programming
Outline
• MySQL
• How it works
• Data Types
• Data Definition Language
• Data Manipulation Language
• MySQL Comments
• Where clause
• Comparison Operators
• ORDER Clause
• LIMIT Clause
• Escaping Characters
• MySQL Joins
• Using MySQL in PHP
• Methods to use
• Connecting to a database
• Querying a database
• Exercise
• Exercise Solution
• Prepared Statements
• Tips and Tricks
• Resources
• Course Project
• Assignment
MySQL
MySQL is a Relational Database Management System
(RDBMS) which stores data in a structured way ( in tables ).
It allows for retrieving data using Structured Query Language
(SQL).
MySQL Server
Web Server
( Apache with PHP )
Web Browser
Request
Query
Resultset
Response
How it works
How tables look like ?
id name salary job_title
1 Ahmed 100 Developer
2 Mohamed 200 Doctor
3 Sara 300 Engineer
4 Marwa 400 Designer
How it works
• In MySQL, we can have multiple databases, every
database has an unlimited amount of tables.
• A table holds data about some entity ( person, employee,
etc ).
• The table consists of number of columns, each column
can have a data type ( char, int, float, etc… )
Data Types
Size Name Range Example
1 TINYINT
-128 TO 127
[0 to 255 if UNSIGNED]
10
2 SMALLINT
-32,768 to 32,767
[0 to 65,535]
30000
3 MEDIUMINT
-8,388,608 to 8,388,607
[0 to 16,777,215]
8000000
4 INT
-/+2.147E+9
[0 to 4.294E+9]
80000000
8 BIGINT
-/+9.223E+18
[0 to 18.45E+18]
80000000000
4 FLOAT p=0-24 4.333333
8 DOUBLE
Min=+/-2.225E-308
Max=+/-1.798E+308
.000000000000000000
003
arbitrary
DECIMAL[(M,[D])]
Stored as string
Max Range = DOUBLE range33333.4444
M CHAR(M)
M=0-255 Characters, FIXED.
Right padded with spaces.
Hello There
M VARCHAR(M)
M=0-65,535 Characters
M=0-255 <v5.0.3
Hello There
Data Types
Size Name Range Example
arbitrary TINYTEXT 0-255 Characters Hello There
arbitrary TEXT 0-65,535 Char's Hello There
arbitrary MEDIUMTEXT 0-16,777,215 Char's Hello There
arbitrary LONGTEXT 0-4,294,967,295 Char's Hello There
arbitrary BINARY[(M)] M=0-255 bytes, FIXED.
arbitrary VARBINARY(M)
0-65,535 bytes
M=0-255 <v5.0.3
arbitrary TINYBLOB 0-255 bytes
arbitrary BLOB 0-65,535 bytes
arbitrary MEDIUMBLOB 0-16,777,215 bytes
arbitrary LONGBLOB 0-4,294,967,295 bytes
3 DATE
"1000-01-01" - "9999-12-
31"
2010-01-01
8 DATETIME
"1000-01-01 00:00:00" -
"9999-12-31 23:59:59"
2010-01-01 10:12:01
3 TIME "-838:59:59" - "838:59:59" 10:12:01
4 TIMESTAMP
19700101000000 -
2037+
19700101000000
Data Definition Language
DDL in the language MySQL use to define its data structures (
databases and tables ).
Example :
CREATE TABLE employees (
id INT PRIMARY KEY,
first_name CHAR(50) NULL,
last_name CHAR(75) NOT NULL,
salary INT NOT NULL DEFAULT 0,
dateofbirth DATE NULL
);
Data Definition Language
Altering tables:
Adding or removing columns or changing the data types of
columns.
Examples:
ALTER TABLE employees ADD salary INT(11);
ALTER TABLE employees MODIFY salary FLOAT(10,5);
ALTER TABLE employees DROP salary;
Data Definition Language
Removing a table:
DROP table employees
Removing a database:
DROP DATABASE db_name;
Data Manipulation Language
DML is the language used by MySQL to manipulate data (
select, insert, update, delete )
SELECT statement:
It is used to get data from a table.
Example :
SELECT * FROM employees
The previous statement should select all the data from the employees
table.
SELECT first_name FROM employees
This should return the column “first_name”
Data Manipulation Language
INSERT statements
They are used to insert a new row into a table.
Examples:
INSERT INTO employees SET id=1, first_name='John',
last_name='Steve', dateofbirth = '1970-01-01‘
INSERT INTO employees (id, first_name, last_name,
dateofbirth ) values ( '2', ‘John', 'Steve', '1970-01-01' )
Data Manipulation Language
UPDATE statements
These statements are used to update (change) data.
Example:
UPDATE employees SET first_name = ‘Mohamed’
This will update all the rows in the employees table setting
the “first_name” to “Mohamed”
Data Manipulation Language
DELETE statements
These statements are used delete rows from a table.
Example:
DELETE FROM employees;
This will delete all rows from employees table.
MySQL Comments
Just like any other programming language, MySQL has ways
to comment code.
1. -- one line comment
2. # one line comment
3. /*
Multi
Line
Comment
*/
Where clause
Where clauses are used to restrict the operations to a limited
number of rows (the rows the satisfy this condition).
Examples:
SELECT * FROM employees WHERE first_name = ‘Mohamed’
DELETE FROM employees WHERE first_name = ‘John’
Update employees SET first_name = ‘Mohamed’ WHERE
last_name = ‘Ahmed’
Comparison Operators
Operator Description
= Equals
!= Not Equals
<> Not Equals
>= Greater than or equal
<= Less than or equal
IS NULL True if the field is not null, false otherwise
IS NOT NULL True if the field is null, false otherwise
BETWEEN … AND … Checks if the value is between the specified numbers
NOT BETWEEN … AND … Checks if the value is not between the specified numbers
IN ( …, …, …, ) Checks if the value is in the specified list
NOT IN Checks if the value is not in the specified list
LIKE Checks if the value is like the specified string.
NOT LIKE Checks if the value is not like the specified string. See next slide
Comparison Operators Examples
SELECT * FROM employees WHERE salary <= 20
SELECT * FROM employees WHERE salary BETWEEN 10 AND
20
SELECT first_name FROM employees WHERE last_name LIKE
‘%ham%’ # percentage ‘%’ matches zero or more characters
SELECT * FROM employees WHERE first_name NOT LIKE
‘__ham__’ # underscore matches 1 character
SELECT * FROM employees WHERE salary IN ( 10, 20, 30 )
ORDER Clause
ORDER clauses are used to order the result set.
Examples:
SELECT * FROM employees ORDER BY first_name ASC
# ASC = ascendingly
SELECT * FROM employees ORDER BY last_name DESC
# DESC = descendingly
LIMIT Clause
Limit clauses are used to limit the number of rows in a result
set.
Examples:
SELECT * FROM employees LIMIT 1
# gets only the first row
SELECT * FROM employees LIMIT 1 , 2
# gets 2 rows starting from the first row ( it gets the second
and third rows )
Escaping Characters
MySQL is similar to PHP when escaping characters :
SELECT * FROM employees WHERE first_name = ‘That’s me’
SELECT * FROM employees WHERE first_name = “That”s
me”
But it adds another method of escaping :
SELECT * FROM employees WHERE first_name = ‘That’’s me’
SELECT * FROM employees WHERE first_name = “That””s
me”
MySQL Joins
MySQL joins allow us to get data from multiple tables in the
same query. Suppose we have the following tables:
id name salary job_title
1 Ahmed 100 Developer
2 Mohamed 200 Doctor
3 Sara 300 Engineer
4 Marwa 400 Designer
id model CC employee_id
1 BMW 1600 1
2 Hyundai 1600 2
3 Honda 1800 3
4 Fiat 1600 4
Employees table
Cars Table
MySQL Joins
The previous tables are employees and cars tables. Every car
has an owner which is an employee.
If we need to get data from these 2 tables, we will need to
join them like the following :
SELECT employees.name, cars.model FROM employees, cars
WHERE employee.id = cars.id
name model
Ahmed BMW
Mohamed Hyundai
Sara Honda
Marwa Fiat
Result set
Using MySQL in PHP
To achieve dynamism, a connection between a language and
database is essential.
PHP has a great MySQL support. There are various methods/
approaches that we could use to connect to MySQL in PHP.
Methods to use
We have 3 methods of code styles that we can use to
connect to MySQL in PHP.
1- Procedural approach.
2- MySQLi approach.
3- PDO ( PHP Data Objects ) approach.
We Will user PDO because it is OOP and it supports named
parameters and exceptions plus it has a good abstraction
model that supports many drivers.
Connecting to database
<?php
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
try {
$connection = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
Querying a database
Here we will need to display the last name of the people
with first_name = ‘Mohamed’.
<?php
$sql = "SELECT * FROM employees WHERE first_name =
'Mohamed'";
$result = $connection->query($sql);
foreach ($result as $row) {
print $row['last_name'] . "<br/>";
}
?>
Querying a database
Inserting a new row into employees table :
<?php
$sql = “INSERT INTO employees SET first_name = ‘Ahmed’,
last_name = ‘Gamal’, salary = 300";
$connection->query($sql);
?>
Querying a database
Getting the number of rows in the result set:
<?php
$sql = "SELECT * FROM employees WHERE first_name =
'Mohamed'";
$result = $connection->query($sql);
echo “Number of rows : “ . $result->rowCount();
?>
Exercise
Write a PHP application the inserts a new employee into the
‘employees’ table. There should be a form that looks like the
following wireframe :
Exercise Solution
We will have a script named “form.php” with the following
HTML:
<html>
<body>
<form action="add.php" method="post" >
<ul style="list-style-type: none;">
<li><label for="first_name">First name</label>
<input type="text" name="first_name" id="first_name" />
</li>
<li><label for="last_name">Last name</label>
<input type="text" name="last_name" id="last_name" />
</li>
<li><label for="salary">Salary</label>
<input type="text" name="salary" id="salary" />
</li>
<li><label for="dateofbirth">Date of birth</label>
<input type="text" name="dateofbirth" id="dateofbirth" />
</li>
<li><input type="submit" name="submit" value="submit" /></li>
</ul>
</form>
</body>
</html>
Exercise Solution
The other script is called “add.php” which contains :
<?php
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
try {
$connection = new PDO($dsn, $user, $password);
$sql = "INSERT INTO employees SET first_name = '" . $connection->quote($_POST['first_name']) . "',
last_name = '" . $connection->quote($_POST['last_name']) . "', salary = " . $connection->quote($_POST['salary'])
. ", dateofbirth = '" . $connection->quote($_POST['dateofbirth']) . "'";
$connection->query($sql);
echo "Record has been added.";
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
Escaping values passed to MySQL
It is advised that any values sent to MySQL should be
escaped using the function called “quote” (like the previous
example). In addition to preventing syntax errors in SQL
statements, it is a top security concern ( google “SQL
injection”, for more information about this type of security
issue).
PDO::quote($str);
Prepared statements
Prepared statements are the ability to set up a statement
once, and then execute it many times with different
parameters.
Example :
SELECT * FROM employees WHERE first_name = ?
SELECT * FROM employees WHERE first_name = :first_name
Prepared statements
One of the key advantages of prepared statements is the
ability to bind parameters.
Binding parameters can be done using one of the
approaches:
1- The question marks “?”.
2- Named parameters ( e.g. “:first_name”, “:last_name”, etc).
Prepared statements
1- Question marks:
<?php
$connection = new PDO($dsn, $user, $password);
$sql = "INSERT INTO employees SET first_name = ? , last_name = ?, salary = ?,
dateofbirth = ?";
$sth = $connection->prepare($sql);
$sth->bindParam(1, $_POST['first_name']);
$sth->bindParam(2, $_POST['last_name']);
$sth->bindParam(3, $_POST['salary']);
$sth->bindParam(4, $_POST['dateofbirth']);
$sth->execute()
?>
Prepared statements
2-Named parameters:
<?php
$sql = "INSERT INTO employees SET first_name = :first_name , last_name =
:last_name, salary = :salary, dateofbirth = :dateofbirth";
$sth = $connection->prepare($sql);
$sth->bindParam(':first_name', $_POST['first_name']);
$sth->bindParam(':last_name', $_POST['last_name']);
$sth->bindParam(':salary', $_POST['salary']);
$sth->bindParam(':dateofbirth', $_POST['dateofbirth']);
$sth->execute();
?>
Prepared statements
Why to use prepared statements:
1- Security; as the developer is not responsible for escaping
parameters passed to MySQL.
2- MySQL parses each query before executing it, so if we are
going to execute the same query with different data values,
prepared statements are the optimized solution since the
query will be compiled ( prepared ) only one time, and then
the data will be substituted in the query each time we
execute it.
Resources
http://dev.mysql.com/doc/
http://php.net/manual/en/book.mysql.php
http://www.php.net/manual/en/intro.pdo.php
Course Project
Detailed explanation of the project. The project document
will be uploaded to the course group.
Assignment
Using the employees table, write a PHP code snippet that
does the following:
1- Shows all the entries in the table.
2- Deletes an entry.
3- Edits an entry.
4- Adds a new entry.
The resulting application should look like PHPMyAdmin
interface.
What's Next?
• Course Project and Performance tips & best practices
Questions?

More Related Content

What's hot

Introduction in php
Introduction in phpIntroduction in php
Introduction in php
Bozhidar Boshnakov
 
Php variables (english)
Php variables (english)Php variables (english)
Php variables (english)
Mahmoud Masih Tehrani
 
PHP PPT FILE
PHP PPT FILEPHP PPT FILE
PHP PPT FILE
AbhishekSharma2958
 
PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & Arrays
Henry Osborne
 
php 2 Function creating, calling, PHP built-in function
php 2 Function creating, calling,PHP built-in functionphp 2 Function creating, calling,PHP built-in function
php 2 Function creating, calling, PHP built-in function
tumetr1
 
Php variables
Php variablesPhp variables
Php variables
Ritwik Das
 
Object-Oriented Programming with PHP (part 1)
Object-Oriented Programming with PHP (part 1)Object-Oriented Programming with PHP (part 1)
Object-Oriented Programming with PHP (part 1)
Bozhidar Boshnakov
 
Class 5 - PHP Strings
Class 5 - PHP StringsClass 5 - PHP Strings
Class 5 - PHP Strings
Ahmed Swilam
 
Web 8 | Introduction to PHP
Web 8 | Introduction to PHPWeb 8 | Introduction to PHP
Web 8 | Introduction to PHP
Mohammad Imam Hossain
 
Web 9 | OOP in PHP
Web 9 | OOP in PHPWeb 9 | OOP in PHP
Web 9 | OOP in PHP
Mohammad Imam Hossain
 
Web 10 | PHP with MySQL
Web 10 | PHP with MySQLWeb 10 | PHP with MySQL
Web 10 | PHP with MySQL
Mohammad Imam Hossain
 
Php pattern matching
Php pattern matchingPhp pattern matching
Php pattern matching
JIGAR MAKHIJA
 
Web 4 | Core JavaScript
Web 4 | Core JavaScriptWeb 4 | Core JavaScript
Web 4 | Core JavaScript
Mohammad Imam Hossain
 
Introduction to Clean Code
Introduction to Clean CodeIntroduction to Clean Code
Introduction to Clean Code
Julio Martinez
 
Web 11 | AJAX + JSON + PHP
Web 11 | AJAX + JSON + PHPWeb 11 | AJAX + JSON + PHP
Web 11 | AJAX + JSON + PHP
Mohammad Imam Hossain
 
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
Pete McFarlane
 
Php server variables
Php server variablesPhp server variables
Php server variables
JIGAR MAKHIJA
 
Php mysql
Php mysqlPhp mysql
Php mysql
Manish Jain
 

What's hot (20)

Introduction in php
Introduction in phpIntroduction in php
Introduction in php
 
Php variables (english)
Php variables (english)Php variables (english)
Php variables (english)
 
PHP PPT FILE
PHP PPT FILEPHP PPT FILE
PHP PPT FILE
 
PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & Arrays
 
php 2 Function creating, calling, PHP built-in function
php 2 Function creating, calling,PHP built-in functionphp 2 Function creating, calling,PHP built-in function
php 2 Function creating, calling, PHP built-in function
 
Php variables
Php variablesPhp variables
Php variables
 
Object-Oriented Programming with PHP (part 1)
Object-Oriented Programming with PHP (part 1)Object-Oriented Programming with PHP (part 1)
Object-Oriented Programming with PHP (part 1)
 
Php & my sql
Php & my sqlPhp & my sql
Php & my sql
 
Class 5 - PHP Strings
Class 5 - PHP StringsClass 5 - PHP Strings
Class 5 - PHP Strings
 
Web 8 | Introduction to PHP
Web 8 | Introduction to PHPWeb 8 | Introduction to PHP
Web 8 | Introduction to PHP
 
Operators in PHP
Operators in PHPOperators in PHP
Operators in PHP
 
Web 9 | OOP in PHP
Web 9 | OOP in PHPWeb 9 | OOP in PHP
Web 9 | OOP in PHP
 
Web 10 | PHP with MySQL
Web 10 | PHP with MySQLWeb 10 | PHP with MySQL
Web 10 | PHP with MySQL
 
Php pattern matching
Php pattern matchingPhp pattern matching
Php pattern matching
 
Web 4 | Core JavaScript
Web 4 | Core JavaScriptWeb 4 | Core JavaScript
Web 4 | Core JavaScript
 
Introduction to Clean Code
Introduction to Clean CodeIntroduction to Clean Code
Introduction to Clean Code
 
Web 11 | AJAX + JSON + PHP
Web 11 | AJAX + JSON + PHPWeb 11 | AJAX + JSON + PHP
Web 11 | AJAX + JSON + PHP
 
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
 
Php server variables
Php server variablesPhp server variables
Php server variables
 
Php mysql
Php mysqlPhp mysql
Php mysql
 

Viewers also liked

Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented Programming
Ahmed Swilam
 
Class 4 - PHP Arrays
Class 4 - PHP ArraysClass 4 - PHP Arrays
Class 4 - PHP Arrays
Ahmed Swilam
 
Class 1 - World Wide Web Introduction
Class 1 - World Wide Web IntroductionClass 1 - World Wide Web Introduction
Class 1 - World Wide Web Introduction
Ahmed Swilam
 
Class 6 - PHP Web Programming
Class 6 - PHP Web ProgrammingClass 6 - PHP Web Programming
Class 6 - PHP Web Programming
Ahmed Swilam
 
Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHP
Bradley Holt
 
PHP MVC Tutorial 2
PHP MVC Tutorial 2PHP MVC Tutorial 2
PHP MVC Tutorial 2Yang Bruce
 
PHPUnit testing to Zend_Test
PHPUnit testing to Zend_TestPHPUnit testing to Zend_Test
PHPUnit testing to Zend_Test
Michelangelo van Dam
 
Intro To Mvc Development In Php
Intro To Mvc Development In PhpIntro To Mvc Development In Php
Intro To Mvc Development In Phpfunkatron
 
Functions in php
Functions in phpFunctions in php
Functions in php
Mudasir Syed
 
Database Systems - Introduction (Chapter 1)
Database Systems - Introduction (Chapter 1)Database Systems - Introduction (Chapter 1)
Database Systems - Introduction (Chapter 1)
Vidyasagar Mundroy
 
Why to choose laravel framework
Why to choose laravel frameworkWhy to choose laravel framework
Why to choose laravel framework
Bo-Yi Wu
 
How to choose web framework
How to choose web frameworkHow to choose web framework
How to choose web framework
Bo-Yi Wu
 
Php & mysql course syllabus
Php & mysql course syllabusPhp & mysql course syllabus
Php & mysql course syllabus
Papitha Velumani
 
Class and Objects in PHP
Class and Objects in PHPClass and Objects in PHP
Class and Objects in PHP
Ramasubbu .P
 
Enterprise-Class PHP Security
Enterprise-Class PHP SecurityEnterprise-Class PHP Security
Enterprise-Class PHP Security
ZendCon
 

Viewers also liked (20)

Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented Programming
 
Class 4 - PHP Arrays
Class 4 - PHP ArraysClass 4 - PHP Arrays
Class 4 - PHP Arrays
 
Class 1 - World Wide Web Introduction
Class 1 - World Wide Web IntroductionClass 1 - World Wide Web Introduction
Class 1 - World Wide Web Introduction
 
Class 6 - PHP Web Programming
Class 6 - PHP Web ProgrammingClass 6 - PHP Web Programming
Class 6 - PHP Web Programming
 
Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHP
 
Php mysql ppt
Php mysql pptPhp mysql ppt
Php mysql ppt
 
Php Presentation
Php PresentationPhp Presentation
Php Presentation
 
PHP MVC Tutorial 2
PHP MVC Tutorial 2PHP MVC Tutorial 2
PHP MVC Tutorial 2
 
PHPUnit testing to Zend_Test
PHPUnit testing to Zend_TestPHPUnit testing to Zend_Test
PHPUnit testing to Zend_Test
 
Intro To Mvc Development In Php
Intro To Mvc Development In PhpIntro To Mvc Development In Php
Intro To Mvc Development In Php
 
Functions in php
Functions in phpFunctions in php
Functions in php
 
Php course-syllabus
Php course-syllabusPhp course-syllabus
Php course-syllabus
 
Introduction to php web programming - get and post
Introduction to php  web programming - get and postIntroduction to php  web programming - get and post
Introduction to php web programming - get and post
 
Introduction to php web programming - sessions and cookies
Introduction to php   web programming - sessions and cookiesIntroduction to php   web programming - sessions and cookies
Introduction to php web programming - sessions and cookies
 
Database Systems - Introduction (Chapter 1)
Database Systems - Introduction (Chapter 1)Database Systems - Introduction (Chapter 1)
Database Systems - Introduction (Chapter 1)
 
Why to choose laravel framework
Why to choose laravel frameworkWhy to choose laravel framework
Why to choose laravel framework
 
How to choose web framework
How to choose web frameworkHow to choose web framework
How to choose web framework
 
Php & mysql course syllabus
Php & mysql course syllabusPhp & mysql course syllabus
Php & mysql course syllabus
 
Class and Objects in PHP
Class and Objects in PHPClass and Objects in PHP
Class and Objects in PHP
 
Enterprise-Class PHP Security
Enterprise-Class PHP SecurityEnterprise-Class PHP Security
Enterprise-Class PHP Security
 

Similar to Class 8 - Database Programming

Data Manipulation Language.pptx
Data Manipulation Language.pptxData Manipulation Language.pptx
Data Manipulation Language.pptx
EllenGracePorras
 
Introduction to-sql
Introduction to-sqlIntroduction to-sql
Introduction to-sql
BG Java EE Course
 
ADBMS unit 1.pdfsdgdsgdsgdsgdsgdsgdsgdsg
ADBMS unit 1.pdfsdgdsgdsgdsgdsgdsgdsgdsgADBMS unit 1.pdfsdgdsgdsgdsgdsgdsgdsgdsg
ADBMS unit 1.pdfsdgdsgdsgdsgdsgdsgdsgdsg
zmulani8
 
Class XII-UNIT III - SQL and MySQL Notes_0.pdf
Class XII-UNIT III - SQL and MySQL Notes_0.pdfClass XII-UNIT III - SQL and MySQL Notes_0.pdf
Class XII-UNIT III - SQL and MySQL Notes_0.pdf
rohithlingineni1
 
ALL ABOUT SQL AND RDBMS
ALL ABOUT SQL AND RDBMSALL ABOUT SQL AND RDBMS
ALL ABOUT SQL AND RDBMS
gaurav koriya
 
SQL PPT.pptx
SQL PPT.pptxSQL PPT.pptx
SQL PPT.pptx
PriyaPandey767008
 
lect 2.pptx
lect 2.pptxlect 2.pptx
lect 2.pptx
HermanGaming
 
Learning sql from w3schools
Learning sql from w3schoolsLearning sql from w3schools
Learning sql from w3schools
farhan516
 
Database management system by Neeraj Bhandari ( Surkhet.Nepal )
Database management system by Neeraj Bhandari ( Surkhet.Nepal )Database management system by Neeraj Bhandari ( Surkhet.Nepal )
Database management system by Neeraj Bhandari ( Surkhet.Nepal )Neeraj Bhandari
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SabrinaShanta2
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SaiMiryala1
 
Basic SQL Statments
Basic SQL StatmentsBasic SQL Statments
Basic SQL Statments
Umair Shakir
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
BhupendraShahi6
 
Chapter8 my sql revision tour
Chapter8 my sql revision tourChapter8 my sql revision tour
Chapter8 my sql revision tour
KV(AFS) Utarlai, Barmer (Rajasthan)
 
Sql intro
Sql introSql intro
Sql introglubox
 
Sql notes, sql server,sql queries,introduction of SQL, Beginner in SQL
Sql notes, sql server,sql queries,introduction of SQL, Beginner in SQLSql notes, sql server,sql queries,introduction of SQL, Beginner in SQL
Sql notes, sql server,sql queries,introduction of SQL, Beginner in SQL
Prashant Kumar
 
Chapter – 6 SQL Lab Tutorial.pdf
Chapter – 6 SQL Lab Tutorial.pdfChapter – 6 SQL Lab Tutorial.pdf
Chapter – 6 SQL Lab Tutorial.pdf
TamiratDejene1
 

Similar to Class 8 - Database Programming (20)

Data Manipulation Language.pptx
Data Manipulation Language.pptxData Manipulation Language.pptx
Data Manipulation Language.pptx
 
Introduction to-sql
Introduction to-sqlIntroduction to-sql
Introduction to-sql
 
Sql 2006
Sql 2006Sql 2006
Sql 2006
 
ADBMS unit 1.pdfsdgdsgdsgdsgdsgdsgdsgdsg
ADBMS unit 1.pdfsdgdsgdsgdsgdsgdsgdsgdsgADBMS unit 1.pdfsdgdsgdsgdsgdsgdsgdsgdsg
ADBMS unit 1.pdfsdgdsgdsgdsgdsgdsgdsgdsg
 
Class XII-UNIT III - SQL and MySQL Notes_0.pdf
Class XII-UNIT III - SQL and MySQL Notes_0.pdfClass XII-UNIT III - SQL and MySQL Notes_0.pdf
Class XII-UNIT III - SQL and MySQL Notes_0.pdf
 
ALL ABOUT SQL AND RDBMS
ALL ABOUT SQL AND RDBMSALL ABOUT SQL AND RDBMS
ALL ABOUT SQL AND RDBMS
 
SQL PPT.pptx
SQL PPT.pptxSQL PPT.pptx
SQL PPT.pptx
 
lect 2.pptx
lect 2.pptxlect 2.pptx
lect 2.pptx
 
MYSQL.ppt
MYSQL.pptMYSQL.ppt
MYSQL.ppt
 
Learning sql from w3schools
Learning sql from w3schoolsLearning sql from w3schools
Learning sql from w3schools
 
Database management system by Neeraj Bhandari ( Surkhet.Nepal )
Database management system by Neeraj Bhandari ( Surkhet.Nepal )Database management system by Neeraj Bhandari ( Surkhet.Nepal )
Database management system by Neeraj Bhandari ( Surkhet.Nepal )
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
 
Basic SQL Statments
Basic SQL StatmentsBasic SQL Statments
Basic SQL Statments
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
 
Chapter8 my sql revision tour
Chapter8 my sql revision tourChapter8 my sql revision tour
Chapter8 my sql revision tour
 
Sql intro
Sql introSql intro
Sql intro
 
Sql notes, sql server,sql queries,introduction of SQL, Beginner in SQL
Sql notes, sql server,sql queries,introduction of SQL, Beginner in SQLSql notes, sql server,sql queries,introduction of SQL, Beginner in SQL
Sql notes, sql server,sql queries,introduction of SQL, Beginner in SQL
 
Chapter – 6 SQL Lab Tutorial.pdf
Chapter – 6 SQL Lab Tutorial.pdfChapter – 6 SQL Lab Tutorial.pdf
Chapter – 6 SQL Lab Tutorial.pdf
 
SQL -PHP Tutorial
SQL -PHP TutorialSQL -PHP Tutorial
SQL -PHP Tutorial
 

Recently uploaded

Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 

Recently uploaded (20)

Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 

Class 8 - Database Programming

  • 2. Outline • MySQL • How it works • Data Types • Data Definition Language • Data Manipulation Language • MySQL Comments • Where clause • Comparison Operators • ORDER Clause • LIMIT Clause • Escaping Characters • MySQL Joins • Using MySQL in PHP • Methods to use • Connecting to a database • Querying a database • Exercise • Exercise Solution • Prepared Statements • Tips and Tricks • Resources • Course Project • Assignment
  • 3. MySQL MySQL is a Relational Database Management System (RDBMS) which stores data in a structured way ( in tables ). It allows for retrieving data using Structured Query Language (SQL). MySQL Server Web Server ( Apache with PHP ) Web Browser Request Query Resultset Response
  • 4. How it works How tables look like ? id name salary job_title 1 Ahmed 100 Developer 2 Mohamed 200 Doctor 3 Sara 300 Engineer 4 Marwa 400 Designer
  • 5. How it works • In MySQL, we can have multiple databases, every database has an unlimited amount of tables. • A table holds data about some entity ( person, employee, etc ). • The table consists of number of columns, each column can have a data type ( char, int, float, etc… )
  • 6. Data Types Size Name Range Example 1 TINYINT -128 TO 127 [0 to 255 if UNSIGNED] 10 2 SMALLINT -32,768 to 32,767 [0 to 65,535] 30000 3 MEDIUMINT -8,388,608 to 8,388,607 [0 to 16,777,215] 8000000 4 INT -/+2.147E+9 [0 to 4.294E+9] 80000000 8 BIGINT -/+9.223E+18 [0 to 18.45E+18] 80000000000 4 FLOAT p=0-24 4.333333 8 DOUBLE Min=+/-2.225E-308 Max=+/-1.798E+308 .000000000000000000 003 arbitrary DECIMAL[(M,[D])] Stored as string Max Range = DOUBLE range33333.4444 M CHAR(M) M=0-255 Characters, FIXED. Right padded with spaces. Hello There M VARCHAR(M) M=0-65,535 Characters M=0-255 <v5.0.3 Hello There
  • 7. Data Types Size Name Range Example arbitrary TINYTEXT 0-255 Characters Hello There arbitrary TEXT 0-65,535 Char's Hello There arbitrary MEDIUMTEXT 0-16,777,215 Char's Hello There arbitrary LONGTEXT 0-4,294,967,295 Char's Hello There arbitrary BINARY[(M)] M=0-255 bytes, FIXED. arbitrary VARBINARY(M) 0-65,535 bytes M=0-255 <v5.0.3 arbitrary TINYBLOB 0-255 bytes arbitrary BLOB 0-65,535 bytes arbitrary MEDIUMBLOB 0-16,777,215 bytes arbitrary LONGBLOB 0-4,294,967,295 bytes 3 DATE "1000-01-01" - "9999-12- 31" 2010-01-01 8 DATETIME "1000-01-01 00:00:00" - "9999-12-31 23:59:59" 2010-01-01 10:12:01 3 TIME "-838:59:59" - "838:59:59" 10:12:01 4 TIMESTAMP 19700101000000 - 2037+ 19700101000000
  • 8. Data Definition Language DDL in the language MySQL use to define its data structures ( databases and tables ). Example : CREATE TABLE employees ( id INT PRIMARY KEY, first_name CHAR(50) NULL, last_name CHAR(75) NOT NULL, salary INT NOT NULL DEFAULT 0, dateofbirth DATE NULL );
  • 9. Data Definition Language Altering tables: Adding or removing columns or changing the data types of columns. Examples: ALTER TABLE employees ADD salary INT(11); ALTER TABLE employees MODIFY salary FLOAT(10,5); ALTER TABLE employees DROP salary;
  • 10. Data Definition Language Removing a table: DROP table employees Removing a database: DROP DATABASE db_name;
  • 11. Data Manipulation Language DML is the language used by MySQL to manipulate data ( select, insert, update, delete ) SELECT statement: It is used to get data from a table. Example : SELECT * FROM employees The previous statement should select all the data from the employees table. SELECT first_name FROM employees This should return the column “first_name”
  • 12. Data Manipulation Language INSERT statements They are used to insert a new row into a table. Examples: INSERT INTO employees SET id=1, first_name='John', last_name='Steve', dateofbirth = '1970-01-01‘ INSERT INTO employees (id, first_name, last_name, dateofbirth ) values ( '2', ‘John', 'Steve', '1970-01-01' )
  • 13. Data Manipulation Language UPDATE statements These statements are used to update (change) data. Example: UPDATE employees SET first_name = ‘Mohamed’ This will update all the rows in the employees table setting the “first_name” to “Mohamed”
  • 14. Data Manipulation Language DELETE statements These statements are used delete rows from a table. Example: DELETE FROM employees; This will delete all rows from employees table.
  • 15. MySQL Comments Just like any other programming language, MySQL has ways to comment code. 1. -- one line comment 2. # one line comment 3. /* Multi Line Comment */
  • 16. Where clause Where clauses are used to restrict the operations to a limited number of rows (the rows the satisfy this condition). Examples: SELECT * FROM employees WHERE first_name = ‘Mohamed’ DELETE FROM employees WHERE first_name = ‘John’ Update employees SET first_name = ‘Mohamed’ WHERE last_name = ‘Ahmed’
  • 17. Comparison Operators Operator Description = Equals != Not Equals <> Not Equals >= Greater than or equal <= Less than or equal IS NULL True if the field is not null, false otherwise IS NOT NULL True if the field is null, false otherwise BETWEEN … AND … Checks if the value is between the specified numbers NOT BETWEEN … AND … Checks if the value is not between the specified numbers IN ( …, …, …, ) Checks if the value is in the specified list NOT IN Checks if the value is not in the specified list LIKE Checks if the value is like the specified string. NOT LIKE Checks if the value is not like the specified string. See next slide
  • 18. Comparison Operators Examples SELECT * FROM employees WHERE salary <= 20 SELECT * FROM employees WHERE salary BETWEEN 10 AND 20 SELECT first_name FROM employees WHERE last_name LIKE ‘%ham%’ # percentage ‘%’ matches zero or more characters SELECT * FROM employees WHERE first_name NOT LIKE ‘__ham__’ # underscore matches 1 character SELECT * FROM employees WHERE salary IN ( 10, 20, 30 )
  • 19. ORDER Clause ORDER clauses are used to order the result set. Examples: SELECT * FROM employees ORDER BY first_name ASC # ASC = ascendingly SELECT * FROM employees ORDER BY last_name DESC # DESC = descendingly
  • 20. LIMIT Clause Limit clauses are used to limit the number of rows in a result set. Examples: SELECT * FROM employees LIMIT 1 # gets only the first row SELECT * FROM employees LIMIT 1 , 2 # gets 2 rows starting from the first row ( it gets the second and third rows )
  • 21. Escaping Characters MySQL is similar to PHP when escaping characters : SELECT * FROM employees WHERE first_name = ‘That’s me’ SELECT * FROM employees WHERE first_name = “That”s me” But it adds another method of escaping : SELECT * FROM employees WHERE first_name = ‘That’’s me’ SELECT * FROM employees WHERE first_name = “That””s me”
  • 22. MySQL Joins MySQL joins allow us to get data from multiple tables in the same query. Suppose we have the following tables: id name salary job_title 1 Ahmed 100 Developer 2 Mohamed 200 Doctor 3 Sara 300 Engineer 4 Marwa 400 Designer id model CC employee_id 1 BMW 1600 1 2 Hyundai 1600 2 3 Honda 1800 3 4 Fiat 1600 4 Employees table Cars Table
  • 23. MySQL Joins The previous tables are employees and cars tables. Every car has an owner which is an employee. If we need to get data from these 2 tables, we will need to join them like the following : SELECT employees.name, cars.model FROM employees, cars WHERE employee.id = cars.id name model Ahmed BMW Mohamed Hyundai Sara Honda Marwa Fiat Result set
  • 24. Using MySQL in PHP To achieve dynamism, a connection between a language and database is essential. PHP has a great MySQL support. There are various methods/ approaches that we could use to connect to MySQL in PHP.
  • 25. Methods to use We have 3 methods of code styles that we can use to connect to MySQL in PHP. 1- Procedural approach. 2- MySQLi approach. 3- PDO ( PHP Data Objects ) approach. We Will user PDO because it is OOP and it supports named parameters and exceptions plus it has a good abstraction model that supports many drivers.
  • 26. Connecting to database <?php $dsn = 'mysql:dbname=testdb;host=127.0.0.1'; $user = 'dbuser'; $password = 'dbpass'; try { $connection = new PDO($dsn, $user, $password); } catch (PDOException $e) { echo 'Connection failed: ' . $e->getMessage(); } ?>
  • 27. Querying a database Here we will need to display the last name of the people with first_name = ‘Mohamed’. <?php $sql = "SELECT * FROM employees WHERE first_name = 'Mohamed'"; $result = $connection->query($sql); foreach ($result as $row) { print $row['last_name'] . "<br/>"; } ?>
  • 28. Querying a database Inserting a new row into employees table : <?php $sql = “INSERT INTO employees SET first_name = ‘Ahmed’, last_name = ‘Gamal’, salary = 300"; $connection->query($sql); ?>
  • 29. Querying a database Getting the number of rows in the result set: <?php $sql = "SELECT * FROM employees WHERE first_name = 'Mohamed'"; $result = $connection->query($sql); echo “Number of rows : “ . $result->rowCount(); ?>
  • 30. Exercise Write a PHP application the inserts a new employee into the ‘employees’ table. There should be a form that looks like the following wireframe :
  • 31. Exercise Solution We will have a script named “form.php” with the following HTML: <html> <body> <form action="add.php" method="post" > <ul style="list-style-type: none;"> <li><label for="first_name">First name</label> <input type="text" name="first_name" id="first_name" /> </li> <li><label for="last_name">Last name</label> <input type="text" name="last_name" id="last_name" /> </li> <li><label for="salary">Salary</label> <input type="text" name="salary" id="salary" /> </li> <li><label for="dateofbirth">Date of birth</label> <input type="text" name="dateofbirth" id="dateofbirth" /> </li> <li><input type="submit" name="submit" value="submit" /></li> </ul> </form> </body> </html>
  • 32. Exercise Solution The other script is called “add.php” which contains : <?php $dsn = 'mysql:dbname=testdb;host=127.0.0.1'; $user = 'dbuser'; $password = 'dbpass'; try { $connection = new PDO($dsn, $user, $password); $sql = "INSERT INTO employees SET first_name = '" . $connection->quote($_POST['first_name']) . "', last_name = '" . $connection->quote($_POST['last_name']) . "', salary = " . $connection->quote($_POST['salary']) . ", dateofbirth = '" . $connection->quote($_POST['dateofbirth']) . "'"; $connection->query($sql); echo "Record has been added."; } catch (PDOException $e) { echo 'Connection failed: ' . $e->getMessage(); } ?>
  • 33. Escaping values passed to MySQL It is advised that any values sent to MySQL should be escaped using the function called “quote” (like the previous example). In addition to preventing syntax errors in SQL statements, it is a top security concern ( google “SQL injection”, for more information about this type of security issue). PDO::quote($str);
  • 34. Prepared statements Prepared statements are the ability to set up a statement once, and then execute it many times with different parameters. Example : SELECT * FROM employees WHERE first_name = ? SELECT * FROM employees WHERE first_name = :first_name
  • 35. Prepared statements One of the key advantages of prepared statements is the ability to bind parameters. Binding parameters can be done using one of the approaches: 1- The question marks “?”. 2- Named parameters ( e.g. “:first_name”, “:last_name”, etc).
  • 36. Prepared statements 1- Question marks: <?php $connection = new PDO($dsn, $user, $password); $sql = "INSERT INTO employees SET first_name = ? , last_name = ?, salary = ?, dateofbirth = ?"; $sth = $connection->prepare($sql); $sth->bindParam(1, $_POST['first_name']); $sth->bindParam(2, $_POST['last_name']); $sth->bindParam(3, $_POST['salary']); $sth->bindParam(4, $_POST['dateofbirth']); $sth->execute() ?>
  • 37. Prepared statements 2-Named parameters: <?php $sql = "INSERT INTO employees SET first_name = :first_name , last_name = :last_name, salary = :salary, dateofbirth = :dateofbirth"; $sth = $connection->prepare($sql); $sth->bindParam(':first_name', $_POST['first_name']); $sth->bindParam(':last_name', $_POST['last_name']); $sth->bindParam(':salary', $_POST['salary']); $sth->bindParam(':dateofbirth', $_POST['dateofbirth']); $sth->execute(); ?>
  • 38. Prepared statements Why to use prepared statements: 1- Security; as the developer is not responsible for escaping parameters passed to MySQL. 2- MySQL parses each query before executing it, so if we are going to execute the same query with different data values, prepared statements are the optimized solution since the query will be compiled ( prepared ) only one time, and then the data will be substituted in the query each time we execute it.
  • 40. Course Project Detailed explanation of the project. The project document will be uploaded to the course group.
  • 41. Assignment Using the employees table, write a PHP code snippet that does the following: 1- Shows all the entries in the table. 2- Deletes an entry. 3- Edits an entry. 4- Adds a new entry. The resulting application should look like PHPMyAdmin interface.
  • 42. What's Next? • Course Project and Performance tips & best practices

Editor's Notes

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43