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

Terminology Data Types SQL Queries PHPMySQL Examples

This document provides an introduction to relational databases and SQL. It discusses key concepts like tables, rows, columns, data types, primary keys, and relationships. It explains how to design tables to model real-world entities and relationships. It also demonstrates some basic SQL commands like SELECT, WHERE, and ORDER BY. Finally, it discusses setting up a shopping cart as a use case, showing how to properly model the relationship between users and products through a separate join table rather than modifying the core tables.

Uploaded by

ramu
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
64 views

Terminology Data Types SQL Queries PHPMySQL Examples

This document provides an introduction to relational databases and SQL. It discusses key concepts like tables, rows, columns, data types, primary keys, and relationships. It explains how to design tables to model real-world entities and relationships. It also demonstrates some basic SQL commands like SELECT, WHERE, and ORDER BY. Finally, it discusses setting up a shopping cart as a use case, showing how to properly model the relationship between users and products through a separate join table rather than modifying the core tables.

Uploaded by

ramu
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

Database Intro

Terminology
Data Types
SQL queries
PHP/MySQL
Examples
Relational Databases
● Formal (mathematical) basis
● Stores "relationships" by storing common
values in more than one table.
● Not the only kind of database
– object databases
– hierarchical
– network

Database Intro (MySQL/PHP) 2


Tables
● Each database is made up of one or more
tables.
– tables have names, typically a word that describes
what information is held in the table.
– A table is defined by a list of the value names/types
that compose each record held in the table.
– Each name/type is called a column.
– Each record is called a row.

Database Intro (MySQL/PHP) 3


Example Table
with Three Records
columns

LastName FirstName DateOfBirth Username Password


Smith Joe 1909-03-22 joes niners
Jones Sally 1956-1-14 joness elvis
Potter Harold 1990-3-4 harry muggle

rows (records)

Database Intro (MySQL/PHP) 4


Possible Schema
● Table People
LastName: varchar(30)
FirstName: varchar(30)
DateOfBirth: date
Username: varchar(20)
Password: varchar(10)

Database Intro (MySQL/PHP) 5


Data Types
● Varies (a little) from one vendor to another...
● Numeric Types
– Integer various sizes: Small/Tiny/Medium...
– Floating point various sizes: Float, Double, ...
● String Types
– varchar: variable length strings (up to some max)
– char: fixed length strings.
– and others...
● A number of Date/Time data types

Database Intro (MySQL/PHP) 6


Column (field) names
● Some people like to prefix all field names with
something related to the table name:
● Table People
pLastName: varchar(30)
pFirstName: varchar(30)
pDateOfBirth: date
pUsername: varchar(20)
pPassword: varchar(10)

Database Intro (MySQL/PHP) 7


phpMySql

Database Intro (MySQL/PHP) 8


Field Attributes
● Is it legal for there to be a record where a field
is empty (NULL) ?
● Number attributes:
– signed vs. unsigned
– autoincrement (every record gets a unique number)
● Default values
● Collation:
– for strings, what alphabetic ordering is used when
comparing strings?
Database Intro (MySQL/PHP) 9
Keys and Indexes
● The Database system build indexes based on
the value of certain fields (called keys).
– this speeds up the process of looking for records
based on the value of the field.
● Every table needs a primary key
– a field whose value will be unique among all
records.
● You can specify the primary key, or let MySql
do it for you (sometimes as a combination of
multiple fields).
Database Intro (MySQL/PHP) 10
SQL
● Structured Query Language
● An english-like language used to express
database operations.
– the database system understands SQL
– the application sends commands to the database
as strings containing SQL.
● in some environments this is actually hidden from the
programmer – libraries generate the SQL automatically.

Database Intro (MySQL/PHP) 11


SQL in use

Local
Application

SQL

Database
Remote SQL
Server
Application
(process)

Database Intro (MySQL/PHP) 12


Some of the basic SQL commands
● SELECT - lookup data.
● INSERT – create a new record.
● UPDATE – change existing records.
● DELETE – remove some records.

There are lots more commands, but these


provide what we need.

Database Intro (MySQL/PHP) 13


The SELECT command
● SELECT is used to extract data from a table
(possibly multiple tables).
● We have to specify:
– which table(s)
– what part of each record we want (what fields)
● We can specify:
– what subset of records we want (what rows).
– how to order the results
– limit on how many records can be returned.
– lots of other options
Database Intro (MySQL/PHP) 14
Simple SELECT
SQL keywords

SELECT FirstName, LastName FROM People

what columns (fields) we


want from each record

The name of the table

Database Intro (MySQL/PHP) 15


Initial table

Database Intro (MySQL/PHP) 16


Entering an SQL Query

Database Intro (MySQL/PHP) 17


Query Result

Database Intro (MySQL/PHP) 18


Another SELECT
SQL keyword

SELECT * FROM people WHERE FirstName='Joe'

* means "all columns" Indicates which records


(rows) we want.

Database Intro (MySQL/PHP) 19


Database Intro (MySQL/PHP) 20
Another Query (using a function)

Database Intro (MySQL/PHP) 21


Exercise: Get dbintro Database
● Grab the file labeled "dbintro sample database"
(on the course home page) and save on your
computer.
● Start up your MySQL client (phpMyAdmin or
whatever you are using).
● The file contains SQL commands to create a
database named dbinfo with tabled people and
product – tell your database to process these
SQL commands.

Database Intro (MySQL/PHP) 22


dbintro Tables
Primary Keys

Database Intro (MySQL/PHP) 23


Simple SQL Exercises
● get the first names of all people

● get the names and product Ids of all products


whose price is less than $1.00

Database Intro (MySQL/PHP) 24


Telling the database how to order
the results.
● You can add "ORDER BY" condition to the end
of the query:
SELECT * FROM people ORDER BY LastName

SELECT Name FROM products ORDER BY Price DESC

Descending

SELECT * FROM people ORDER BY DateOfBirth ASC

Ascending
Database Intro (MySQL/PHP) 25
Shopping Cart
● Suppose we want to store a user's shopping
cart in the database.
– we need some way to store this information.
– we need to be careful how we set this up, doing it
the wrong way will make the system difficult to
maintain.
● Requirements:
– need to store information on the number of each
product in each users shopping cart.

Database Intro (MySQL/PHP) 26


One Bad Idea
● We could consider this:
– for each person record, add the following fields:
● Snickers: integer
● Candy Corn: integer
● Wax Lips: integer
● Bubble Gum: integer

● Exercise: why is this a bad idea?

Database Intro (MySQL/PHP) 27


Problems
● What if we add new products?
– M&Ms are always a good idea.

● What if we remove products?


– The margin on Bubble Gum is too small to make $.

Database Intro (MySQL/PHP) 28


Another Bad Idea
● We could add a field in each product record for
each user.
– obviously a waste of space.
– we hope we get new users!

● In general we need a solution that does not


require changes to our database schema every
time we change our products.

Database Intro (MySQL/PHP) 29


The Relational in Relation Database
● We want to establish a relationship between
users and products.
– how many of product x is associated with user y.
● We create a new table to represent this
relationship.
– needs to refer to a user.
– needs to refer to a product.
– we also need a quantity (of the product in the
shopping cart).

Database Intro (MySQL/PHP) 30


New Table: cartentries
● Table cartentries
userid: integer
productid: integer
quantity: integer

Why not use FirstName,LastName and


ProductName ?
what if these change? Does it invalidate some
shopping cart entries?
Database Intro (MySQL/PHP) 31
A Picture of the relationship

Database Intro (MySQL/PHP) 32


Exercise: Create cartentries Table
● You can do this via the User Interface, or issue
the following SQL statement:

CREATE TABLE `cartentries` (


`userid` INT NOT NULL ,
`productid` INT NOT NULL ,
`quantity` INT NOT NULL
) TYPE = MYISAM ;

Database Intro (MySQL/PHP) 33


Add some records
● Joe Smith (userid=1) has 3 Candy Corns (productid=2)
● Sally Jones (userid=2) has 1 Candy Corn
● ...

INSERT INTO `cartentries` VALUES (1, 2, 3);


INSERT INTO `cartentries` VALUES (2, 2, 1);
INSERT INTO `cartentries` VALUES (1, 4, 2);
INSERT INTO `cartentries` VALUES (4, 3, 17);

Database Intro (MySQL/PHP) 34


All shopping cart entries

Database Intro (MySQL/PHP) 35


A Join
● You can select information from two tables,
using a relationship (common field value) to join
the tables together.
● The result can contain fields from both tables.
● The result is still a list of records (rows)
– each row contains fields from more than one table.
● For example, we would like to see a list of all
products in all shopping carts, but we want to
see product names (not ids).
Database Intro (MySQL/PHP) 36
Joining products and cartentries
SELECT * FROM cartentries,products WHERE
cartentries.productid=products.productid

--or--

SELECT *
FROM cartentries JOIN products ON
( cartentries.productid =
products.productid )

Database Intro (MySQL/PHP) 37


Join result

Database Intro (MySQL/PHP) 38


SQL Exercises
● A query that retrieves all the information
needed to display a user's shopping cart:
– need list of products:
● product name
● quantity
● price

● We need this for a single user (use userid 2).

Database Intro (MySQL/PHP) 39


Fancier stuff
● SQL SELECT commands can actually do lots
more than just retrieve data:
– can compute things, like the total cost for each item in
the cart: quantity * price:
SELECT *,
cartentries.quantity * products.price AS itemtotal
FROM cartentries, products
WHERE cartentries.productid = products.productid
AND cartentries.userid =1
LIMIT 0 , 30

Database Intro (MySQL/PHP) 40


PHP and MySQL
● To make use of the database with PHP, we
need to do the following:
– establish a connection
– identify the database we want to use
● there can be many databases
– Issue SQL commands (queries)
– Retrieve and process results
● often display as HTML

Database Intro (MySQL/PHP) 41


PHP/MySQL
● Your installation of PHP needs to have MySQL
support (either built-in or as a module). You
tested this in HW1.
● Although we can connect to any MySQL server,
we will use the one running on the same
machine as the web server (your laptop).
– everyone has their own database.

Database Intro (MySQL/PHP) 42


Establishing a Connection
● You need a username and password to access
your MySQL server.
● You need to know what machine the server is
running on.
● You call the php function mysql_connect():
mysql_connect(server,username,password);
● The function returns a PHP resource that is used by other
functions later, or FALSE if the connection fails.

Database Intro (MySQL/PHP) 43


Sample Connection

// establish a connection with the MySQL server


// server is 'localhost'
// user, pass is 'joe', 'abc'
$link = mysql_connect('localhost','joe','abc');
if (! $link) {
echo ("<h3>Error" . mysql_error()."</h3>\n");
exit;
}

Database Intro (MySQL/PHP) 44


Selecting a Database
● Typically an application deals with a single
database (your MySQL server can have many
databases).
You have to tell the server what database you
are using:
mysql_select_db( databasename );
● This function returns a boolean indicating
success or failure.

Database Intro (MySQL/PHP) 45


Example: Selecting a Database

if (mysql_select_db("dbintro")) {
echo "<h3>Connected !</h3>\n";
} else {
echo "Error connecting: " . mysql_error();
exit;
}

Database Intro (MySQL/PHP) 46


Sending a Query
● The query (SQL command) is a string.
– we often need to build these strings based partially
on information from the HTTP request.

mysql_query(SQLstring)

● returns a PHP resource (that we can use later


to get at the results) or FALSE on error.
– For some kinds of SQL commands, returns TRUE
or FALSE Database Intro (MySQL/PHP) 47
Query Example
// get all people records
$res = mysql_query("SELECT * FROM people");
if (! $res) {
echo "<p>Error: ". mysql_error() . "</p>\n";
exit;
}

Database Intro (MySQL/PHP) 48


Getting the results
● The return value from mysql_query can be
used to retrieve the results.
– There are many different PHP functions that can be
used to get individual records/fields.
– We will look at the simplest function :

mysql_result( resource , row , fieldname );


● resource is the return value from mysql_query
● row is a number (the record number in the result)
● fieldname is a string the identifies the field.

Database Intro (MySQL/PHP) 49


How many records (rows)?
mysql_num_rows(resource)

Example:

$res = mysql_query($q);
$num = mysql_num_rows($res);
echo "<p>I found $num records</p>";

Database Intro (MySQL/PHP) 50


Example Code
$res = mysql_query("SELECT * FROM people");
if (! $res){
echo "<h3>Error!</h3>"; exit;
}
echo "<H3>All people found:</H3>\n";
$num = mysql_num_rows($res);
for ($i=0;$i<$num;$i++) {
$f = mysql_result($res,$i,'FirstName');
$l = mysql_result($res,$i,'LastName');
echo "<p>$f $l</p>\n";
}
Database Intro (MySQL/PHP) 51

You might also like