CMPS246 Week14 phpMySQL
CMPS246 Week14 phpMySQL
Web Programming 1
How did you
register for the
course?
Web Programming 2
You accessed a database!
• When you registered for the course, you accessed the university
database.
Web Programming 3
A database is a coherent collection of data
Meaningful data (random assortment of data can’t be referred to as a
database)
• Courses
• Students
• Grades
• Employees
• Patients
• Doctors
• Medical records
• Salaries
Web Programming 4
What is a Database Management System
• Computerized systems that enables users to create and maintain a
database
• General purpose software system DBMS
• DBMS operations on a database
1. Define
2. Construct
3. Manipulate
4. Share DATABASE
5. Protect
6. Maintain
Web Programming 5
Facebook DBMS
• Facebook uses MySQL for the majority of the data you
would consider as “Facebook data” like posts
comments etc..
• It also uses other DBMSs like
• Hbase
• Cassandra
Web Programming 6
Facebook
Datacenters
• Each data center houses
tens of thousands of
computer servers
• massive storage
infrastructure to house
its enormous piles of
data
Web Programming 7
Database ER Model
Web Programming 8
Database Tables
Web Programming 9
Structure Query Language
• Originally was called SEQUEL (Structured English QUEry Language)
• Was designed and implemented at IBM research
• Now the standard language for commercial relational DBMSs
• Has statements for applying the DBMS operations
Data Definition Language (DDL)
Web Programming 10
SQL Commands Chart
SQL
Web Programming 12
SQL
Define Schemas,
create roles,
Relations, Domains, Query Data Update Data
permissions, access
Transaction specific
Views
CREATE SELECT
DROP FROM
ALTER WHERE
TRUNCATE ORDER BY
Web Programming 13
Manipulating the Database by Querying Data
SELECT
Web Programming 14
Querying Data
SELECT projection_attribute(s)
FROM table_name(s)
WHERE selection_join_condition
ORDER BY attribute_name(s)
Web Programming 15
Query with Selection Condition
Web Programming 16
SQL
Define Schemas,
create roles,
Relations, Domains, Query Data Update Data
permissions, access
Transaction specific
Views
TRUNCATE ORDER BY
Web Programming 17
Manipulating the Database by Updating Data
Web Programming 18
Inserting Data
• Use INSERT to add a single tuple o a relation
• Values should be listed in the order of the attributes
• If no attributes are specified, add values for all relation attributes
• Must insert values for NOT NULL attributes
Web Programming 19
Inserting Data
Web Programming 20
Application Programs
Web Programming 21
Websites/Web Applications
• Webpages accessed through the internet/intranet
• Client-served based applications
• Developed in scripting language
• HTML
• PHP
• CSS
• Python
• Javascript
• Others
Web Programming 22
Application Environment
Backend
Frontend Internet
Database
Application
Web Programming 23
Application Environment
Backend as a Service (BaaS)
Frontend Internet
Application
https://youtu.be/iosNuIdQoy8?list=PLl-K7zZEsYLmOF_07IayrTntevxtbUxDL
Web Programming 24
Database Programming Routes
Web Programming 25
Choosing the TechStack
• a set of tools that are used to construct and power an application
• Combination of software applications, and programming languages
Web Programming 26
Find Techstacks
https://techstacks.io/stacks/
Web Programming 27
Database Programming Languages
• Data sublanguage:
database language (SQL)
Web Programming 28
Approaches to Database Programming
• Embedded SQL: Embedding database commands in a host language
Web Programming 29
Impedance Mismatch
• Problems that occur because of differences between the
database model and the programming language model
• Different datatypes (binding datatypes)
• Accessing individual valued from multiset results of queries
(biniding data structures)
Web Programming 30
Sequence of Interaction in DB Programming
1. Establish or open a connection to DB server
• URL of DB server machine
• Login account name and password
2. Interact with DB by submitting queries
• Use SQL statements
• Apply appropriate binding to avoid impedance mismatch
3. Terminate or close DB connection
Web Programming 31
PHP and MySQL
• MySQL is the most popular database system used with PHP.
• PHP 5 and later can work with a MySQL database using:
• MySQLi extension (the "i" stands for improved)
• PDO (PHP Data Objects)
Web Programming 32
Open a Connection to MySQL
Web Programming 33
Create the Database
Web Programming 34
Insert Values
Web Programming 35
Facebook
Datacenters
• Each data center houses
tens of thousands of
computer servers
• massive storage
infrastructure to house
its enormous piles of
data
Web Programming 36
Similar Organizations
• Google
• Amazon
• Twitter
• Instagram
• LinkedIn
Database Systems 37
Big Data Applications
• Social media
• Web links
• User profiles
• Marketing and sales
• Posts and tweets
• Roadmaps
• Spatial data
• Email
Database Systems 38
No Relational model
Database Systems 39
DynamoDB by Amazon in 2004
• Amazon was growing rapidly and was starting to hit the upper scaling
limits of its Oracle database
• Engineers created the Amazon Dynamo database which backed major
internal infrastructure
Database Systems 40
NoSQL Databases
• Not only SQL
• Needed to augment data management needs
• Distributed databases and storage systems
Database Systems 41
SQL NoSQL
Database Systems 42
Popular NoSQL Systems
• Google
• BigTable
• Firebase Realtime Database
• Firestore
• Amazon
• DynamoDB
• Facebook
• Cassandra
Database Systems 44
NoSQL Systems Model Characteristics
• No schema required
• Semi-structured self describing data
• Constraints are programmed within the applications
• Less powerful query language
• Provide functions as API
• CRUD operations (Create, Read, Update, Delete)
• Join need to be implemented in the application program
• Versioning
• Storage of multiple versions of all data items
• Time-stamped data
Database Systems 45
NoSQL Database (JSON Object)
Collection
Table/relation
Document ID
primaryKey
Database Systems 46
Collection of Documents
Database Systems 47
NoSQL Database
• Schemaless
• More flexible
• No need to alter schema to update the data
Database Systems 48
Adding data
Database Systems 49
Relational Model
Database Systems 50
Get a list of attendees for an event
Database Systems 51
How to model this as NoSQL database?
Database Systems 52
Flat Structure
Database Systems 53
Querying Data in SQL
Database Systems 54
Querying Data in NoSQL
Database Systems 55
Example
Database Systems 56
Recommended YouTube Series
https://www.youtube.com/playlist?list=PLl- https://www.youtube.com/playlist?list=PLl-
K7zZEsYLlP-k-RKFa7RyNPa9_wCH2s K7zZEsYLluG5MCVEzXAQ7ACZBCuZgZ
Database Systems 57
Login System
Verification
https://www.youtube.com/watch?v=C-ZSQMbsm7A
Database Systems 58
Creating the Database
Database Systems 59
phpMyAdmin
Database Systems 60
Define constants (config/constants.php)
<?php
define('DB_HOST','localhost');
define('DB_USER','root');
define('DB_PASS','');
define('DB_NAME','user-verification');
Database Systems 61
Connect to database (config/db.php)
<?php
require 'constans.php';
//$con->close();
Database Systems 62
authController.php
• Create controllers/authController.php
Database Systems 63
Check if email already exists
$emailQuery = "SELECT * FROM users WHERE useremail=? LIMIT 1";
$stmt = $con->prepare($emailQuery);
$stmt ->bind_param('s',$email);
$stmt->execute();
$result = $stmt->get_result();
$userCount = $result->num_rows;
$stmt->close();
if($userCount>0){
$errors['email']="Email already exists";
}
Database Systems 64
If no errors, we need to insert user to DB
• Add a password hash for security
• Add a token to be used for email verification
• Set verified to false
if(count($errors)==0){
$password = password_hash($password,PASSWORD_DEFAULT);
$token = bin2hex(random_bytes(50));
$verified = false;
Database Systems 65
Insert user to database
$sql = "INSERT INTO users (username, useremail, verified, token, password)
VALUES (?,?,?,?,?)";
$stmt = $con->prepare($sql);
$stmt ->bind_param('ssbss',$username,$email,$verified,$token,$password);
if($stmt->execute()){
} else {
$errors[‘db_error’]=“Database error: failed to register”;
}
Database Systems 66
Save User info in a session (use across pages)
if ($stmt->execute()){
//login user
$user_id = $con->insert_id;
$_SESSION['id']=$user_id;
$_SESSION['username']=$username;
$_SESSION['email']=$email;
session_start(); $_SESSION['verified']=$verified;
<?php if(!$_SESSION['verified']):?>
<div class="alert alert-warning">
You need to verify your account.
Verfication email sent to you at
<strong><?php echo $_SESSION['email'];?></strong>
</div>
<?php endif ?>
Database Systems 68
index.php
Database Systems 69
login.php
Database Systems 70
Email Verfication
• Add email controller to send registered user an email once new user
is inserted to the database
• Install composer
• Use swiftmailer library
Database Systems 71