Transcript PHP

validated.php
<?php
$title="my basic page\n";
include("top.html");
print "<div>hello, world</div>";
include("bottom.html");
?>
LIS651 lecture 2
Thomas Krichel
2005-04-02
today
• introduction to mySQL
• more on PHP
– functions
– includes
Databases
• Databases are collection of data with
some organization to them.
• The classic example is the relational
database.
• But not all database need to be relational
databases.
Relational databases
• A relational database is a set of tables.
There may be relations between the
tables.
• Each table has a number of record. Each
record has a number of fields.
• When the database is being set up, we fix
– the size of each field
– relationships between tables
Example: Movie database
ID
M1
M2
M3
M4
M5
M6
| title
| director
| date
| Gone with the wind
| F. Ford Coppola | 1963
| Room with a view | Coppola, F Ford | 1985
| High Noon
| Woody Allan
| 1974
| Star Wars
| Steve Spielberg | 1993
| Alien
| Allen, Woody
| 1987
| Blowing in the Wind
| Spielberg, Steven | 1962
• Single table
• No relations between tables, of course
Problem with this database
• All data wrong, but this is just for
illustration.
• Name covered inconsistently. There is no
way to find films by Woody Allan without
having to go through all spelling variations.
• Mistakes are difficult to correct. We have
to wade through all records, a masochist’s
pleasure.
Better movie database
ID | title
M1
| Gone with the wind
M2
| Room with a view
M3
| High Noon
M4 | Star Wars
M5
| Alien
M6
| Blowing in the Wind
ID
D1
D2
D3
| D3
| D2
| director
| D1
| D1
| D2
| 1993
| 1987
| D3
| director name
| birth year
| Ford Coppola, Francis | 1942
| Allan, Woody
| 1957
| Spielberg, Steven
| 1942
| year
| 1963
| 1985
| 1974
| 1962
Relational database
• We have a one to many relationship
between directors and film
– Each film has one director
– Each director has produced many films
• Here it becomes possible for the computer
– To know which films have been directed by
Woody Allen
– To find which films have been directed by a
director born in 1942
Many-to-many relationships
• Each film has one director, but many
actors star in it. Relationship between
actors and films is a many to many
relationship.
• Here are a few actors
ID
A1
A2
A3
| sex
|f
|m
|f
| actor name
| Brigitte Bardot
| George Clooney
| Marilyn Monroe
| birth year
| 1972
| 1927
| 1934
Actor/Movie table
actor id
| movie id
A1
| M4
A2
| M3
A3
| M2
A1
| M5
A1
| M3
A2
| M6
A3
| M4
… as many lines as required
databases in libraries
• Relational databases dominate the world of
structured data
• But not so popular in libraries
– Slow on very large databases (such as
catalogs)
– Library data has nasty ad-hoc relationships, e.g.
• Translation of the first edition of a book
• CD supplement that comes with the print version
Difficult to deal with in a system where all
relations and field have to be set up at the start,
can not be changed easily later.
databases in web sites
• Lots of active web sites are driven by
relational databases. All large active web
sites are.
• The design of a active web site first
involves looking at databases.
• In a shop situation, we have the following
tables
– customers
– products
– orders
– orders_products
SQL
• Once we have the relational database, we
can ask sophisticated questions:
– Which director has had the most female
actors working for him?
– In which years films have been shot that
starred actors born between 1926 and 1935?
• Such questions can be encoded in a
language know as “structured query
language” or SQL. All relational database
vendors implement a dialect of SQL.
mySQL
• They are a very successful, open-source
vendor of SQL software.
• Their product is basically freely available.
• We will learn the mySQL dialect of SQL.
using mySQL
• mySQL is installed on wotan.
• Normally this involves logging into wotan
and issuing commands to a character
interface.
• The command would be
– mysql -u user -p
create database
• This is a mySQL command to create a new
database.
• Example
– create database newbase;
• creates a database newbase
GRANT
• This is a command to create users and give
them privileges. A simplified general syntax
is
GRANT privileges [columns] 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.
user privilegesI
• SELECT
allows users to select (read)
records from tables.
• INSERTallows users to insert new rows into
tables.
• UPDATE
allows users to change values
in existing table rows.
• DELETE
allows users to delete table
rows.
• INDEX allows user to index tables
user privilegesII
• 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 databases or tables.
user privilegesIII
• 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.
REVOKE
• This is the opposite of GRANT.
current setup
• As the super user, I did
create database user_name;
GRANT * 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
– * means all rights
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.
creating tables
• before you do it, set up some examples on
a sheet of paper.
• Here is an example
CREATE TABLE customers (custumer_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);
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 -2**31 and
2**31-1 or between 0 and 2**32-1.
INTEGER is a synonym for INT.
• BIGINT can hold a number between -2**63
and 2**61-1 or between 0 and 2**64-1.
column data types: float
• FLOAT is a floating number on 4 bytes
• DOUBLE is a floating number on 8 bytes
column data types: dates
• DATE is a day from 1000-01-01 to 9999-1231.
• TIME is a time from -838:59:59 to
838:59:59
• DATETIME is a data and time, usually
displayed as YYYY-MM-DD HH:MM:SS
• TIMESTAMP is the number of seconds
since 1970-01-01 at 0 hours. This number
may run out in 2037.
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.
functions
• The PHP function reference is available on
its web site
http://www.php.net/quickref.php. It shows
the impressive array of functions within
PHP.
• But one of the strengths of PHP is that you
can create your own functions as you
please.
• If you recreate one of the built-in functions,
your own function will have no effect.
example
• Stephanie Rubino was an English teacher
and objects to sentences like
You have ordered 1 bottles of Grosswald Pils.
• Let us define a function rubino_print(). It will
take three arguments
– a number to check for plural or singular
– a word for the singular
– a word for the plural
function and parameters
• use the keyword "function" and declare
your parameters, as in:
function rubino_print ($number, $singular,$plural)
{
if($number == 1) {
print "one $singular";
}
else {
print "$number $plural";
}
default arguments
• Sometimes you want to allow a function to
be called without giving all its arguments.
You can do this by declaring a default
value. For the previous example
function thomas_need($thing='beer') {
print "I need $thing\n";
}
thomas_need();
// prints: I need beer;
thomas_need('sleep');
// prints: I need sleep;
rubino_print using common
plurals
function rubino_print ($num, $sing,$plur=1)
{
if($num == 1) {
print "one $sing";
}
elseif($plur ==1) {
print "$num $sing"."s";
}
else {
print "$num $plur";
}
return value
• Up until now we have just looked at the
effect of a function.
• return is a special command that return a
value.
• When return is used, the function is left.
rubino_print with return
function rubino_print ($number, $singular,$plural) {
if($number == 1) {
return "one $singular";
}
return "$number $plural";
}
$order=rubino_print(2,"beer","beers");
print "you ordered $order\n";
// prints: you ordered 2 beers.
visibility of variables
• variables used inside a function are not
visible from the outside. Example
$beer="Karlsberg";
function yankeefy ($name='Sam Adams') {
$beer=$name;
}
yankeefy();
print $beer; // prints: Karlsberg
• the variable inside the function is something
different than the variables outside.
accessing global variables.
• There are two ways to change a global
variable, i.e. one that is defined in the main
script.
• One is just to call it as $GLOBAL['name']
where name is the name of the global
variable.
function yankeefy ($name="Sam Adams") {
$GLOBAL['beer']="name";
}
brewer_quiz.php: introduction
<?php
$brewers=array('Großwald Brauerei','Homburger
Brauhaus', 'Karlsberg Brauerei','Ponter
Hausbrauerei', 'Saarfürst Merziger
Brauhaus','Mettlacher Abtei-Bräu','Körpricher
Landbräu','Brauerei G.A. Bruch','Neufang
Brauerei','Zum Stiefel');
$form_top="<form
action=\"$_SERVER[PHP_SELF]\"
method=\"get\"><p>\n";
$form_submit='<input type="submit" value="I
brewer_quiz.php: form building
function build_form($answer,$comment) {
print "<div>Take the Saarland brewery
challenge</div>\n";
print $GLOBALS['form_top'];
print "<input type=\"text\" name=\"guess\"
value=\"$answer\"/>";
print $GLOBALS['form_submit']; print
$GLOBALS['submit_check'];
print $GLOBALS['form_end']; print $comment;
}
brewer_quiz.php: form
processing
function process_form($answer,$brewers)
{
$r[]=$answer;
foreach($brewers as $brew) {
if($answer == "$brew") {
$r[]='<div>Congradulation! This is
correct!</div>';
return $r;
}
}
$r[]='<div>This is a bad answer, try again!</div>';
return $r;
brewer_quiz.php main part
if($_GET['submitted']) {
$from_form=process_form($_GET['guess'],$brewer
s);
}
build_form($from_form[0],$from_form[1]) ;
?>
working with many source files
• Many times it is useful to split a PHP script
into several files.
• PHP has two mechanisms.
• require(file) requires the to be included. If
the file is not there, PHP exits with an error.
• include(file) includes the file.
require() and include()
• Both assume that you leave PHP. Thus
within your included file you can write
simple HTML.
• If you want to include PHP in your included
file, you have to surround it by <?php and
?>, just like in a PHP script.
• Here is an example to use include to build
the basic web page.
bottom.html
<p id="validator">
<a
href="http://validator.w3.org/check?uri=referer"><i
mg
style="border: 0pt"
src="http://wotan.liu.edu/valid-xhtml10.png"
alt="Valid XHTML 1.0!" height="31" width="88"
/></a>
</p>
</body>
validated.php
<?php
$title="my basic page\n";
include("top.html");
print "<div>hello, world</div>";
include("bottom.html");
?>
trouble
• $title in the top.html is not understood as
the title. It reads as $title, which means
"idiot" for your web user.
• Even if you replace $title with
<?php $title ?>
$title is empty. The definition from the
outer file is not seen in the included file.
• So you have to split into three files, and
print the title in the main file. I leave that to
you to figure out.
http://openlib.org/home/krichel
Thank you for your attention!