Terminology Data Types SQL Queries PHPMySQL Examples

download Terminology Data Types SQL Queries PHPMySQL Examples

of 51

Transcript of Terminology Data Types SQL Queries PHPMySQL Examples

  • 8/8/2019 Terminology Data Types SQL Queries PHPMySQL Examples

    1/51

    Database Intro

    Terminology

    Data Types

    SQL queries

    PHP/MySQL

    Examples

  • 8/8/2019 Terminology Data Types SQL Queries PHPMySQL Examples

    2/51

    Database Intro (MySQL/PHP) 2

    Relational Databases

    Formal (mathematical) basis

    Stores "relationships" by storing commonvalues in more than one table.

    Not the only kind of database

    object databases

    hierarchical

    network

  • 8/8/2019 Terminology Data Types SQL Queries PHPMySQL Examples

    3/51

    Database Intro (MySQL/PHP) 3

    Tables

    Each database is made up of one or moretables.

    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.

  • 8/8/2019 Terminology Data Types SQL Queries PHPMySQL Examples

    4/51

    Database Intro (MySQL/PHP) 4

    Example Tablewith Three Records

    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

    columns

    rows (records)

  • 8/8/2019 Terminology Data Types SQL Queries PHPMySQL Examples

    5/51

    Database Intro (MySQL/PHP) 5

    Possible Schema

    Table People

    LastName:varchar(30)

    FirstName:varchar(30)

    DateOfBirth: date

    Username:varchar(20)

    Password:varchar(10)

  • 8/8/2019 Terminology Data Types SQL Queries PHPMySQL Examples

    6/51

    Database Intro (MySQL/PHP) 6

    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

  • 8/8/2019 Terminology Data Types SQL Queries PHPMySQL Examples

    7/51

    Database Intro (MySQL/PHP) 7

    Column (field) names

    Some people like to prefix all field names withsomething related to the table name:

    Table People

    pLastName:varchar(30)

    pFirstName:varchar(30)

    pDateOfBirth: date

    pUsername:varchar(20)

    pPassword:varchar(10)

  • 8/8/2019 Terminology Data Types SQL Queries PHPMySQL Examples

    8/51

    Database Intro (MySQL/PHP) 8

    phpMySql

  • 8/8/2019 Terminology Data Types SQL Queries PHPMySQL Examples

    9/51

    Database Intro (MySQL/PHP) 9

    Field Attributes

    Is it legalfor there to be a record where a fieldis 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?

  • 8/8/2019 Terminology Data Types SQL Queries PHPMySQL Examples

    10/51

    Database Intro (MySQL/PHP) 10

    Keys and Indexes

    The Database system build indexes based onthe 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 aprimary key

    a field whose value will be unique among allrecords.

    You can specify the primary key, or let MySqldo it for you (sometimes as a combination ofmultiple fields).

  • 8/8/2019 Terminology Data Types SQL Queries PHPMySQL Examples

    11/51

    Database Intro (MySQL/PHP) 11

    SQL

    Structured Query Language

    An english-like language used to expressdatabase operations.

    the database system understands SQL

    the application sends commands to the databaseas strings containing SQL.

    in some environments this is actually hidden from theprogrammer libraries generate the SQL automatically.

  • 8/8/2019 Terminology Data Types SQL Queries PHPMySQL Examples

    12/51

    Database Intro (MySQL/PHP) 12

    SQL in use

    LocalApplication

    Database

    Server(process)

    SQL

    RemoteApplication SQL

  • 8/8/2019 Terminology Data Types SQL Queries PHPMySQL Examples

    13/51

    Database Intro (MySQL/PHP) 13

    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 theseprovide what we need.

  • 8/8/2019 Terminology Data Types SQL Queries PHPMySQL Examples

    14/51

    Database Intro (MySQL/PHP) 14

    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

  • 8/8/2019 Terminology Data Types SQL Queries PHPMySQL Examples

    15/51

    Database Intro (MySQL/PHP) 15

    Simple SELECT

    SELECT FirstName, LastName FROMPeople

    what columns (fields) wewant from each record

    The name of the table

    SQL keywords

  • 8/8/2019 Terminology Data Types SQL Queries PHPMySQL Examples

    16/51

    Database Intro (MySQL/PHP) 16

    Initial table

  • 8/8/2019 Terminology Data Types SQL Queries PHPMySQL Examples

    17/51

    Database Intro (MySQL/PHP) 17

    Entering an SQL Query

  • 8/8/2019 Terminology Data Types SQL Queries PHPMySQL Examples

    18/51

  • 8/8/2019 Terminology Data Types SQL Queries PHPMySQL Examples

    19/51

    Database Intro (MySQL/PHP) 19

    Another SELECT

    SELECT * FROMpeopleWHERE FirstName='Joe'

    * means "all columns" Indicates which records

    (rows) we want.

    SQL keyword

  • 8/8/2019 Terminology Data Types SQL Queries PHPMySQL Examples

    20/51

    Database Intro (MySQL/PHP) 20

  • 8/8/2019 Terminology Data Types SQL Queries PHPMySQL Examples

    21/51

    Database Intro (MySQL/PHP) 21

    Another Query (using a function)

  • 8/8/2019 Terminology Data Types SQL Queries PHPMySQL Examples

    22/51

    Database Intro (MySQL/PHP) 22

    Exercise: Get dbintro Database

    Grab the file labeled "dbintro sample database"(on the course home page) and save on yourcomputer.

    Start up your MySQL client (phpMyAdmin orwhatever you are using).

    The file contains SQL commands to create adatabase named dbinfo with tabled people andproduct tell your database to process theseSQL commands.

  • 8/8/2019 Terminology Data Types SQL Queries PHPMySQL Examples

    23/51

    Database Intro (MySQL/PHP) 23

    dbintro Tables

    PrimaryKeys

  • 8/8/2019 Terminology Data Types SQL Queries PHPMySQL Examples

    24/51

    Database Intro (MySQL/PHP) 24

    Simple SQL Exercises

    get the first names of all people

    get the names and product Ids of all productswhose price is less than $1.00

    T lli th d t b h t d

  • 8/8/2019 Terminology Data Types SQL Queries PHPMySQL Examples

    25/51

    Database Intro (MySQL/PHP) 25

    Telling the database how to orderthe results.

    You can add "ORDER BY" condition to the endof the query:

    SELECT * FROM people ORDER BY LastName

    SELECT Name FROM products ORDER BY Price DESC

    SELECT * FROM people ORDER BY DateOfBirth ASC

    Descending

    Ascending

  • 8/8/2019 Terminology Data Types SQL Queries PHPMySQL Examples

    26/51

    Database Intro (MySQL/PHP) 26

    Shopping Cart

    Suppose we want to store a user's shoppingcart in the database.

    we need some way to store this information.

    we need to be careful how we set this up, doing itthe wrong way will make the system difficult tomaintain.

    Requirements:

    need to store information on the number of eachproduct in each users shopping cart.

  • 8/8/2019 Terminology Data Types SQL Queries PHPMySQL Examples

    27/51

    Database Intro (MySQL/PHP) 27

    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?

  • 8/8/2019 Terminology Data Types SQL Queries PHPMySQL Examples

    28/51

    Database Intro (MySQL/PHP) 28

    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 $.

  • 8/8/2019 Terminology Data Types SQL Queries PHPMySQL Examples

    29/51

    Database Intro (MySQL/PHP) 29

    Another Bad Idea

    We could add a field in each product record foreach user.

    obviously a waste of space.

    we hope we get new users!

    In general we need a solution that does notrequire changes to our database schema everytime we change our products.

  • 8/8/2019 Terminology Data Types SQL Queries PHPMySQL Examples

    30/51

    Database Intro (MySQL/PHP) 30

    The Relationalin Relation Database

    We want to establish a relationship betweenusers and products.

    how many of product x is associated with user y.

    We create a new table to represent thisrelationship.

    needs to refer to a user.

    needs to refer to a product.

    we also need a quantity (of the product in theshopping cart).

  • 8/8/2019 Terminology Data Types SQL Queries PHPMySQL Examples

    31/51

    Database Intro (MySQL/PHP) 31

    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?

  • 8/8/2019 Terminology Data Types SQL Queries PHPMySQL Examples

    32/51

    Database Intro (MySQL/PHP) 32

    A Picture of the relationship

  • 8/8/2019 Terminology Data Types SQL Queries PHPMySQL Examples

    33/51

    Database Intro (MySQL/PHP) 33

    Exercise: Create cartentries Table

    You can do this via the User Interface, or issuethe following SQL statement:

    CREATE TABLE `cartentries` (`userid` INT NOT NULL ,`productid` INT NOT NULL ,`quantity` INT NOT NULL

    ) TYPE = MYISAM ;

  • 8/8/2019 Terminology Data Types SQL Queries PHPMySQL Examples

    34/51

    Database Intro (MySQL/PHP) 34

    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);

    All shopping cart entries

  • 8/8/2019 Terminology Data Types SQL Queries PHPMySQL Examples

    35/51

    Database Intro (MySQL/PHP) 35

    All shopping cart entries

  • 8/8/2019 Terminology Data Types SQL Queries PHPMySQL Examples

    36/51

    Database Intro (MySQL/PHP) 36

    A Join

    You can select information from two tables,using a relationship (common field value) tojointhe 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 allproducts in all shopping carts, but we want tosee product names (not ids).

  • 8/8/2019 Terminology Data Types SQL Queries PHPMySQL Examples

    37/51

    Database Intro (MySQL/PHP) 37

    Joiningproducts and cartentries

    SELECT * FROM cartentries,products WHEREcartentries.productid=products.productid

    --or--

    SELECT *

    FROM cartentries JOIN products ON

    ( cartentries.productid =products.productid )

  • 8/8/2019 Terminology Data Types SQL Queries PHPMySQL Examples

    38/51

    Database Intro (MySQL/PHP) 38

    Join result

  • 8/8/2019 Terminology Data Types SQL Queries PHPMySQL Examples

    39/51

    Database Intro (MySQL/PHP) 39

    SQL Exercises

    A query that retrieves all the informationneeded 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).

    F i ff

  • 8/8/2019 Terminology Data Types SQL Queries PHPMySQL Examples

    40/51

    Database Intro (MySQL/PHP) 40

    Fancier stuff

    SQL SELECT commands can actually do lotsmore than just retrieve data:

    can compute things, like the total cost for each item inthe cart: quantity * price:

    SELECT *,

    cartentries.quantity * products.price AS itemtotal

    FROM cartentries, products

    WHERE cartentries.productid = products.productidAND cartentries.userid =1

    LIMIT 0 , 30

    PHP d M SQL

  • 8/8/2019 Terminology Data Types SQL Queries PHPMySQL Examples

    41/51

    Database Intro (MySQL/PHP) 41

    PHP and MySQL

    To make use of the database with PHP, weneed 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

    PHP/M SQL

  • 8/8/2019 Terminology Data Types SQL Queries PHPMySQL Examples

    42/51

    Database Intro (MySQL/PHP) 42

    PHP/MySQL

    Your installation of PHP needs to have MySQLsupport (either built-in or as a module). Youtested this in HW1.

    Although we can connect to any MySQL server,we will use the one running on the samemachine as the web server (your laptop).

    everyone has their own database.

    E t bli hi C ti

  • 8/8/2019 Terminology Data Types SQL Queries PHPMySQL Examples

    43/51

    Database Intro (MySQL/PHP) 43

    Establishing a Connection

    You need a username and password to accessyour MySQL server.

    You need to know what machine the server is

    running on. You call the php functionmysql_connect():

    mysql_connect(server,username,password);

    The function returns a PHP resource that is used by otherfunctions later, or FALSE if the connection fails.

    S l C ti

  • 8/8/2019 Terminology Data Types SQL Queries PHPMySQL Examples

    44/51

    Database Intro (MySQL/PHP) 44

    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 ("Error" . mysql_error()."\n");

    exit;

    }

    S l ti D t b

  • 8/8/2019 Terminology Data Types SQL Queries PHPMySQL Examples

    45/51

    Database Intro (MySQL/PHP) 45

    Selecting a Database

    Typically an application deals with a singledatabase (your MySQL server can have manydatabases).

    You have to tell the server what database youare using:

    mysql_select_db( databasename );

    This function returns a boolean indicatingsuccess or failure.

    Example: Selecting a Database

  • 8/8/2019 Terminology Data Types SQL Queries PHPMySQL Examples

    46/51

    Database Intro (MySQL/PHP) 46

    Example: Selecting a Database

    if (mysql_select_db("dbintro")) {

    echo "Connected !\n";

    } else {echo "Error connecting: " . mysql_error();

    exit;

    }

    Sending a Query

  • 8/8/2019 Terminology Data Types SQL Queries PHPMySQL Examples

    47/51

    Database Intro (MySQL/PHP) 47

    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 laterto get at the results) or FALSE on error.

    For some kinds of SQL commands, returns TRUEor FALSE

    Query Example

  • 8/8/2019 Terminology Data Types SQL Queries PHPMySQL Examples

    48/51

    Database Intro (MySQL/PHP) 48

    Query Example

    // get all people records$res = mysql_query("SELECT * FROM people");

    if (! $res) {

    echo "

    Error: ". mysql_error() . "

    \n";exit;

    }

    Getting the results

  • 8/8/2019 Terminology Data Types SQL Queries PHPMySQL Examples

    49/51

    Database Intro (MySQL/PHP) 49

    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

    rowis a number (the record number in the result) fieldname is a string the identifies the field.

    How many records (rows)?

  • 8/8/2019 Terminology Data Types SQL Queries PHPMySQL Examples

    50/51

    Database Intro (MySQL/PHP) 50

    How many records (rows)?

    mysql_num_rows(resource)

    Example:

    $res = mysql_query($q);

    $num = mysql_num_rows($res);

    echo "

    I found $num records

    ";

    Example Code

  • 8/8/2019 Terminology Data Types SQL Queries PHPMySQL Examples

    51/51

    Database Intro (MySQL/PHP) 51

    Example Code

    $res = mysql_query("SELECT * FROM people");if (! $res){

    echo "Error!"; exit;

    }

    echo "All people found:\n";

    $num = mysql_num_rows($res);

    for ($i=0;$i