LIS651%20lecture%202%20mySQL%20and%20PHP%20mySQL%20functions - PowerPoint PPT Presentation

About This Presentation
Title:

LIS651%20lecture%202%20mySQL%20and%20PHP%20mySQL%20functions

Description:

Arrays seem to cause the most confusion in student understanding. ... UPDATE [LOW_PRIORITY] [IGNORE] table SET column1=expression1, column2=expression2... – PowerPoint PPT presentation

Number of Views:186
Avg rating:3.0/5.0
Slides: 52
Provided by: open2
Learn more at: http://openlib.org
Category:

less

Transcript and Presenter's Notes

Title: LIS651%20lecture%202%20mySQL%20and%20PHP%20mySQL%20functions


1
LIS651 lecture 2mySQL and PHP mySQL functions
  • Thomas Krichel
  • 2007-04-01

2
today
  • Today I talk about
  • arrays and table (again, since this causes
    problems)
  • some basic mySQL commands
  • a PHP interface to mySQL called mysqli
  • Today you do
  • create a table with phpmyadmin
  • write PHP scripts to read/write data to the table
    using the web

3
arrays and tables
  • Arrays seem to cause the most confusion in
    student understanding.
  • An array is just a way for PHP to address
    multiple things as one variable.
  • Arrays can be of multiple dimensions.
  • This is typically the case when the array
    represents the contents of a table.

4
example
  • Here is an example table
  • name type brewer rating price
  • Bruch Festbock dark Bruch good 1.18
  • Balitka 8 wheat Baltika good 0.88
  • Budweiser light A.-B. lousy 0.99
  • typically, records appear in lines and fields in
    columns.

5
one way to set out the table
  • beers0'name''Bruch Landbock'
  • beers0'type''dark'
  • beers0'brewer''Bruch
  • .
  • beers2'price'0.99
  • Here, records are a numeric array. Fields are
    string arrays that are members of the numeric
    array.
  • What instruction would improve the rating of
    Budweiser?

6
another way
  • beerarray( 'name'gt 'Bruch Landbock',
    typegt'dark', 'brewer'gt 'Bruch',
    'rating'gt'good', pricegt'1.18')
  • beersbeer
  • beerarray( 'name'gt'Budweiser', typegt'light',
    'brewer'gt'A.-B.', 'rating'gt'lousy',
    pricegt0.99)
  • beersbeer
  • This will give the same array as before.

7
yet another way, as a matrix
  • namesarray('Bruch Landbock', 'Baltika
    8','Budweiser')
  • typesarray( 'dark', 'wheat', 'light' )
  • brewersarray( 'Bruch', 'Baltika', 'A.-B.')
  • ratingsarray( 'good', 'good', 'lousy')
  • pricesarray(1.18,0.88,0.99)
  • beersarray( names, types,brewers,ratings,
    prices)
  • What instruction would improve the rating of
    Budweiser?

8
another way to set out the table
  • namesarray('Bruch Landbock', 'Baltika
    8','Budweiser')
  • typesarray( 'dark', 'wheat', 'light' )
  • brewersarray( 'Bruch', 'Baltika', 'A.-B.')
  • ratingsarray( 'good', 'good', 'lousy')
  • pricesarray(1.18,0.88,0.99)
  • beersarray( 'name'gtnames, 'type'gttypes,
    'brewer'gt brewers, 'rating'gtratings,
    'price'gtprices)
  • What instruction would improve the rating of
    Budweiser?

9
using mySQL
  • mySQL server is installed on wotan.
  • It is a daemon that deals with client requests.
  • There is also a tty client installed. To use it
    you log into wotan and type
  • mysql -u user -p
  • and then you type in your password.
  • We will cover this in the last lecture.

10
uppercase and lowercase
  • Traditionally SQL commands are written with
    uppercase.
  • mySQL commands are really case-insensitive.
  • But variable names in the commands are
    case-sensitive. I will therefore write them in
    lowercase.

11
CREATE DATABASE
  • CREATE DATABASE a mySQL command to create a new
    database.
  • Example
  • CREATE DATABASE newbase
  • creates a database newbase.
  • You have no privileges to create a database.
  • But I dont see the reason you wanting to do that.

12
GRANT
  • This is a command to create users and give them
    privileges. A simplified general syntax is
  • GRANT privileges ON item TO user_name
  • IDENTIFIED BY 'password' WITH GRANT OPTION
  • If you use WITH GRANT OPTION, you allow the user
    to grant other users the privileges that you have
    given to her.

13
user privileges I
  • SELECT allows users to select (read) records from
    tables. Generally select is a word used for read
    in databases.
  • INSERT allows users to insert new rows into
    tables.
  • UPDATE allows users to change values in existing
    table rows.
  • DELETE allows users to delete table rows
    (records)
  • INDEX allows user to index tables

14
user privileges II
  • ALTER allows users to change the structure of the
    database.
  • adding columns
  • renaming columns or tables
  • changing the data types of tables
  • DROP allows users to delete databases or tables.
    In general, the word drop refers to deleting
    database or tables.

15
user privileges III
  • CREATE allows users to create new databases or
    tables. If a specific table or database is
    mentioned in the GRANT statement, users can only
    create that database or table, which will mean
    that they have to drop it first.
  • USAGE allows users nothing. This is a useful
    point to start with if you just want to create a
    user.

16
REVOKE
  • This is the opposite of GRANT.

17
current setup
  • As the super user, I did
  • CREATE DATABASE user_name
  • GRANT ALL ON user_name TO user_name IDENTIFIED BY
    'secret_word' WITH GRANT OPTION
  • Here
  • user_name is your wotan user name
  • secret_word is your secret word
  • ALL means all rights

18
create a web user
  • You do not want to give the same access rights to
    people coming in from the web as you have.
  • You do not want to do this. You personally have
    too many privileges.
  • I have yet to find out how you can create a web
    user by yourself.

19
creating tables
  • This is done conveniently in phpmyadmin.
  • Here is an example for real SQL code
  • CREATE TABLE customers (customer_id INT UNSIGNED
  • NOT NULL AUTO_INCREMENT PRIMARY KEY, name
  • CHAR(50) NOT NULL, address CHAR(100) NOT NULL,
    email CHAR(40), state CHAR(2) NOT NULL)

20
column data types
  • TINYINT can hold a number between -128 and 127 or
    between 0 to 255. BIT or BOOL are synonyms for
    the TINYINT.
  • SMALLINT can hold a number between -32768 and
    32767 or 0 and 65535
  • INT can hold a number between -231 and 231-1
    or between 0 and 232-1. INTEGER is a synonym
    for INT.
  • BIGINT can hold a number between -263 and
    261-1 or between 0 and 264-1.

21
column data types float
  • FLOAT is a floating number on 4 bytes
  • DOUBLE is a floating number on 8 bytes
  • DECIMAL(x,y) where x is the number of digits
    before the decimal point and y is the number of
    digits after the decimal point.

22
column data types dates
  • DATE is a day from 1000-01-01 to 9999-12-31.
  • TIME is a time from -8385959 to 8385959
  • DATETIME is a date and time, usually displayed as
    YYYY-MM-DD HHMMSS
  • TIMESTAMP is the number of seconds since
    1970-01-01 at 0 hours. This number may run out in
    2037.

23
field options
  • PRIMARY KEY says that this column is a the
    primary key. There can be only one such column.
    Values in the column must be unique.
  • AUTO_INCREMENT can be used on columns that
    contain integer values.
  • NOT NULL requires the field not to be empty.

24
USE
  • USE database tells mySQL to start working with
    the database database.
  • If you have not issued a USE command, you can
    still address a table table by using
    database.table, where datebase is the name of
    your database and table is the name of your
    table. You are using the dot to link the two
    together.

25
addressing database tables columns
  • Let there by a database database with a table
    table and some column column. Then it is
    addressed as database.table.column.
  • Parts of this notation can be left out if it is
    clear what is meant, for example if you have
    issued USE database before, you can leave out the
    database part.

26
INSERT
  • INSERT inserts new rows into a table. In its
    simples form
  • INSERT INTO table VALUES (value1, value2, ..)
  • Example
  • INSERT INTO products VALUES ('','Neufang
    Pils',1.23)
  • Note that in the example, I insert the null
    string in the first column because it is an
    auto_increment.
  • Mark Sandford says If you use an auto_increment
    variable, you may as well have it last.

27
partial INSERT
  • If you are only giving a part of a record, or if
    you want to enter them in a different order you
    will have to give a list of column names.
  • INSERT INTO products (name,id) VALUES ('Neufang
    Pils','')

28
SELECT
  • This is the SQL statement to select rows from a
    table. Here is the full syntax
  • SELECT options columns INTO file_details
  • FROM table WHERE conditions
  • GROUP BY group_type
  • HAVING where_definitions
  • ORDER BY order_type LIMIT limit_criteria
  • PROCEDURE proc_name(arguments)
  • lock_options

29
columns to SELECT
  • You can have a comma-separated list of columns
  • SELECT name, price FROM products
  • You can use the star to get all columns
  • SELECT FROM products

30
WHERE condition to SELECT
  • means equality
  • WHERE id 3
  • gt, lt, gt, lt and ! also work as expected
  • IS NULL tests if the value is null
  • IS NOT NULL
  • IN allows you to give a set
  • WHERE state IN ("NY","NJ","CT")

31
SELECT using multiple tables
  • table1,table2 can be used to join both tables to
    build a big table that can be searched
  • SELECT orders.id FROM customers, orders
  • WHERE customers.id 3
  • This type of join is a Cartesian product aka a
    full join. For each row of the first table, it
    adds rows from the second table.

32
ORDER
  • You can order by a field by saying ORDER BY.
  • You can add ASC or DESC to achieve ascending or
    descending order.
  • SELECT name, address FROM customers ORDER BY name
    ASC

33
LIMIT
  • This can be used to limit the amount of rows.
  • LIMIT 10 19
  • This is useful it web sites where you show a
    selection of the results.
  • This ends the discussion of the SELECT command.

34
UPDATE
  • UPDATE LOW_PRIORITY IGNORE table SET
    column1expression1, column2expression2...
    WHERE condition ORDER BY order_criteria
    LIMIT number
  • This changes values in a row.
  • An example is
  • UPDATE students SET email 'phpguru_at_gmail.com'
  • WHERE name'Janice Insinga'
  • IGNORE instructs to ignore errors.
  • LOW_PRIORITY instructs to delay if the server is
    busy.

35
DELETE
  • DELETE LOW_PRIORITY QUICK IGNORE FROM table
    WHERE condition ORDER BY order_criteria
    LIMIT number
  • Here is a very bad example
  • DELETE FROM customers
  • Here is a good example
  • DELETE FROM customers WHERE
  • customer.name'Thomas Krichel

36
PHP mySQL functions
  • We are using here the new version of PHP mySQL
    function, starting with mysqli_
  • The interface is object-oriented, but can also be
    accessed in a non-object-oriented way. This is
    known as the procedural style, in the
    documentation.
  • You should use the online documentation at
    http//php.net/mysqli

37
error suppression
  • The function mentioned in this library usually
    report any error that has occurred.
  • It can be useful to suppress such errors with the
    PHP error suppression operator _at_.
  • _at_function() will run the function function
    without reporting mistakes.
  • You can then create your own customized mistakes
    by checking for errors every time you run a
    mysqli function. This is useful.

38
mysqli_connect()
  • This is used to establish a connection to the
    mySQL server. It is typically of the form
    mysqli_connect('host', 'user', 'password')
  • Example
  • link mysqli_connect('localhost','boozer','heinek
    en')
  • You can use localhost as the host name for wotan
    talking to itself, but you could also connect to
    other Internet hosts, if you have permission.

39
the mySQL connection with mysqli
  • The mysqli module has the ability to handle
    several connections to the mySQL server.
  • Once a connection is established it is
    represented by the variable returned by
    mysqli_connect().
  • This variable, of type "resource" has the be
    referenced later to let mysqli functions know
    what connection you are using, because there may
    be more than one open at the same time.

40
mysqli_connect_error()
  • This function returns a string with the last
    connection error.
  • link mysqli_connect("localhost", "bad_user",
    "")
  • if (!link) print "Can't connect to localhost.
    The error isltbrgt"
  • print mysqli_connect_error()
  • print "ltbr/gt"
  • Note the use of ! to express Boolean "not".

41
mysqli_error( link )
  • This function return the error from the last
    mySQL command. It returns false if there was no
    error.
  • errormysqli_error(link)
  • if(error)
  • print "mySQL error errorltbr/gt"
  • This function requires the connection as a
    parameter.
  • The value returned from that function is a simple
    string.
  • It is a good idea to check out error messages.

42
mysqli_select_db()
  • This command has the syntax mysqli_select_db(link,
    'database') where link is a resource representing
    a connection and database is the name of a
    database.
  • This tells mySQL that you now want to use the
    database database.
  • mysqli_select_db(link,'beer_shop')
  • It has the same effect as issuing
  • USE beer_shop
  • within mySQL.

43
mysqli_query()
  • mysqli_query(link,query) send the query string
    query to mySQL connection represented by link
  • link mysqli_connect("localhost", "owner",
    "bruch")
  • // you may then add some connection checks
  • query"SELECT FROM beer_shop.customers"
  • resultmysqli_query(link,query)
  • Note that the query itself does not require a
    terminating semicolon.
  • The result is in result.

44
result of mysqli_query()
  • For SELECT, SHOW, DESCRIBE or EXPLAIN mySQL
    queries, mysqli_query() returns a resource that
    can be further examined with mysqli_fetch_array()
    . This is very important function that we look at
    in the next slide.
  • For UPDATE, INSERT, DELETE, DROP and others,
    mysqli_query() returns a Boolean value.

45
examining resulting rows
  • mysqli_fetch_array(result) returns an array that
    is the result row for the resource result
    representing the most recent, or NULL if it the
    last result is reached. Its results in an array
    that contains the columns requested both by
    number and by column name
  • while(columnsmysqli_fetch_array(result))
  • print 'name '.columns'name'
  • print 'first column .columns0

46
examining a specific result
  • mysqli_data_seek(result, number) sets the array
    that is returned by mysqli_fetch_array to a
    number number.
  • while(rowmysqli_fetch_array(result))
  • print 'first column '.row0
  • mysqli_data_seek(result,0)
  • // otherwise the second loop would not work
  • while(rowmysqli_fetch_array(result))
  • print 'first column '.row0

47
mysqli_num_rows()
  • This command has the syntax mysqli_select_db(resul
    t) where the resource result is the result of a
    query.
  • It returns the number of rows that are in the
    result.
  • This is useful in announcing the number results
    before display of results.

48
mysqli_real_escape_string()
  • mysqli_real_escape_string( link,string) returns a
    string escaped for the using in mySQL.
  • name"John O'Guiness"
  • s_namemysqli_real_escape_string(link,name)
  • print s_name // prints John O\'Guiness
  • Note that this function makes a call to mySQL,
    therefore a connection must be established before
    the function can be used.
  • This function guards against SQL injections.

49
mysqli_close(link)
  • This command closes a connection. It requires the
    connection as an argument, so that it knows which
    connection to close.
  • This is the happiest command there is, because it
    means that we have finished.
  • Unfortunately it is not used very often because
    the mySQL connection is closed automatically when
    the script finishes running.

50
extra sha1()
  • This is a function that calculates a combination
    of 40 characters from a string.
  • The result of sha1() can not be translated back
    into the original string.
  • This makes it a good way to store password.
  • s_passwordsha1(password)

51
http//openlib.org/home/krichel
  • Thank you for your attention!
  • Please switch off machines b4 leaving!
Write a Comment
User Comments (0)
About PowerShow.com