PHP and Mysql Tutorial: Introductions The Metadata
PHP and Mysql Tutorial: Introductions The Metadata
"A teacher overheard him say that he was using PHP, and as part of our Zero-Tolerance policy against drug use, he was immediately suspended. No questions asked," said Principal Clyde Thurlow. "We're not quite sure what PHP is, but we suspect it may be a derivative of PCP, or maybe a new designer drug like GHB." Parents are frightened by the discovery of this new menace in their children's school, and are demanding the school do something. "We heard that he found out about PHP at school on the internet. There may even be a PHP web ring operating on school grounds," said irate parent Carol Blessing. "School is supposed to be teaching our kids how to read and write. Not about dangerous drugs like PHP." In response to parental demands the school has reconfigured its internet WatchDog software to block access to all internet sites mentioning PHP. Officials say this should prevent any other students from falling prey like Brett Tyson did. They have also stepped up locker searches and brought in drug sniffing dogs. Interviews with students suggested that PHP use is wide spread around the school, but is particularly concentrated in the geeky nerd population. When contacted by BBspot.com, Brett Tyson said, "I don't know what the hell is going on dude, but this suspension gives me more time for fraggin'. Yee haw!" PHP is a hypertext preprocessor, which sounds very dangerous. It is believed that many users started by using Perl and moved on to the more powerful PHP. For more information on how to recognize if your child may be using PHP please visit http://www.php.net.
1 2
Introductions
The Metadata
2 parts, each 3 hours
Me You
The Rules
Think before you code! Dont just copy code from here No wimps! This class is hardcore Dont get lost! Questions are required, not optional
5
Our Example
An online store!
Might be edited periodically Dynamic: changes on demand search, change preferences, interact, post, edit
What is PHP?
Software package www.php.net Works with web server software Similar to: ASP, ColdFusion, Java Server Pages (JSP)
Why a database?
Need to store lots of data! Fast access to data Data must persist Data is structured
10
PHP
"Here is an HTML le for index.php."
www.foo.edu
"Please process index.php."
MySQL
I want index.html.
index.html
query result
I want index.php.
Users computer
11
Users computer
12
The Plan
PHP MySQL Integration Project: online store! today today/tomorrow tomorrow tomorrow
Down to business!
13
14
Statements
PHP code consists of statements Semicolon-terminated Exception: last statement <?php echo ("Hello, world!"); doStuff (); echo ("Goodbye, world!"); ?>
17 18
Code in Courier
Delimiter Examples
Input
<?php printPi(); ?> printPi(); <?php echo(40 + 2); ?> 40 + 2
Hello, world!
Output
A working example Put this in hello.php in Sites folder <HTML><HEAD> <TITLE>Hello!</TITLE></HEAD> <BODY> <?php echo ("Hello, world!");?> </BODY></HTML> Look at <server>/~josti#/hello.php
19 20
3.14159265359 printPi(); 42 40 + 2
Variables
Name preceded by $ No declarations, very weak typing Must begin with letter or underscore Names contain only letters, numbers, underscores
$name = "George";
WARNING: undened variables have NULL value; can use without error!
21 22
Comments
Comment your code! Code is for people, not machines. PHP does this; // ignores this /* PHP ignores all of this */
23
If statements
if ($grade > 64) { echo ("You passed!"); } else { echo ("What a loser!"); } Curly braces only required for more than one statement
24
More tests
if ($grade >= 64 && !($grade > 75)) echo "lucky punk!"; if (calculateMeaningOfLife() == 42) echo "Phew!";
25
Loops
for ($i = 0; $i < $max; $i++) { echo ("iteration " . $i); } Notice the "." - its the string concatenation operator. while (isMoreData()) { printData(); }
27 28
if (name == "Dave") echo "D"; if ($name = "Dave") echo "D"; if ($foo < 6); echo "less!"; if (1 < 4) if (5 > 42) echo "one"; else echo "two";
Exercise
Create a web page that displays your name 500 times. use a for loop. After that works, modify it to also print a line number on each line.
29
30
Arrays
Actually ordered maps keys (strings or ints) to values (stuff in array) $arr = array (5 => 1); echo $arr[5]; // 1 $arr["x"] = 42; remember this for MySQL echo $arr["x"]; // 42
31
Generating tables
<TABLE> <?php $rows = 10; $cols = 3; for ($i = 0; $i < $rows; $i++) { echo "<TR>"; for ($j=0; $j < $cols; $j++) { echo "<TD>row $i,col $j</TD>"; } echo "</TR>"; } ?> </TABLE>
33
Questions?
34
Forms
Two parts form (HTML) form processor (PHP)
The Form
<FORM action="processor.php" method="post"> <INPUT type="text" name="username" size="20"/> <INPUT type="password" name="password" size="20"/> <INPUT type="submit" value="click here!"/> </FORM>
35 36
<FORM action="processor.php" method="post"> <INPUT type="text" name="username" size="20"/> <INPUT type="password" name="password" size="20"/> <INPUT type="submit" value="click here!"/> </FORM>
Method: how browser sends data GET POST Action: where browser sends data INPUT: a eld for data entry
Exercise
Make a form for users to enter their name and favorite color. If their favorite color is the same as yours, print something special.
39
40
PHP include/require
Avoid code duplication include ("header.php"); require ("login.php"); Same, but require fails if its arguments doesnt exist.
41
42
Handling login
Problem: each page wants $username, $password. Solutions? Yes, you.
Cookies
Or: angering ignorant users in one easy step!
Save a little data on users machine Like, say, the username, once they authenticated.
setcookie ("username", $username);
43
44
On to MySQL!
45
46
What is SQL?
Structured Query Language Not English, Spanish, French,... Query: request "Please add Joe to the user list." "Who posted today?"
47
What is MySQL?
Particular implementation of SQL Others: SQLite (included in PHP 5) PostgreSQL MS SQL Server
48
MySQL includes...
mysqld Daemon - runs all the time Server process Manages les that contain actual database mysql Client - runs when you need it Talks to mysqld
49
Relational Databases
50
A good database?
Mug Apple Microsoft Sun DEC Color White Black Green green Price $10 $2 $5 $100
51
A Better Database
ID 0 1 2 Color White Black Green
Colors
ID 0 1 2 3
Price 10 2 5 100
Color 0 1 2 2
Mugs
52
Relational Databases
Avoid Duplication Assign a UNIQUE ID to each row Refer to data in other tables by ID Unambiguous!
Buzzwords
Table: Spreadsheet Database: Collection of tables Row or record: Entry in table Column: Field for entering data Schema: A particular database setup
53
54
Types
Think "kinds" Types of tools: hammer, screwdriver bang (hammer)? OK. turn (screwdriver)? OK. turn (hammer)? No!
55
Your turn!
Design a database schema for a store for your mug collection. Hint: mugs table users table (better record who bought what!) What data do you need? Groups of three
57
Using MySQL
Use mysql client to talk to server ssh (with PuTTY). See blackboard. Login: josti#. Password: international mysql -u josti# -p Now: only type MySQL commands.
58
MySQL commands
use josti#; End commands with semicolons Case InSenSiTiVe show tables;
CREATE TABLE mugs (id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY (ID), description VARCHAR(40), price float); Pattern: create table <table_name> (column denition, column denition, ...) Column denition: <column_name> <type>
59
60
Primary key: unique identier Constraints are your friend! NOT NULL, DEFAULT
61
62
Adding Data
INSERT INTO mugs (description, price) values ('DEC', 100); or: INSERT INTO mugs SET description='DEC', price=100; Add a few records of your own!
63
Getting data
You SELECT the data you want FROM the table it's in. SELECT description, price FROM mugs SELECT description FROM mugs ORDER BY description ASCENDING SELECT description FROM mugs WHERE price < 10
64
INSERT [LOW_PRIORITY | DELAYED] [IGNORE] [INTO] tbl_name [(col_name,...)] VALUES ({expr | DEFAULT},...),(...),... [ ON DUPLICATE KEY UPDATE col_name=expr, ... ] [stuff]: stuff is optional {a | b}: pick a or b, not both. Must have one.
65 66
ALTER [IGNORE] TABLE tbl_name alter_specification [, alter_specification] ... alter_specification: ADD [COLUMN] column_definition [FIRST | AFTER col_name ] | ADD [COLUMN] (column_definition,...) | ADD INDEX [index_name] [index_type] (index_col_name,...) | ADD [CONSTRAINT [symbol]] PRIMARY KEY [index_type] (index_col_name,...) | ADD [CONSTRAINT [symbol]] UNIQUE [index_name] [index_type] (index_col_name,...) | ADD [FULLTEXT|SPATIAL] [index_name] (index_col_name,...) | ADD [CONSTRAINT [symbol]] FOREIGN KEY [index_name] (index_col_name,...) [reference_definition] | ALTER [COLUMN] col_name {SET DEFAULT literal | DROP DEFAULT} | CHANGE [COLUMN] old_col_name column_definition [FIRST|AFTER col_name] | MODIFY [COLUMN] column_definition [FIRST | AFTER col_name] | DROP [COLUMN] col_name | DROP PRIMARY KEY | DROP INDEX index_name | DROP FOREIGN KEY fk_symbol | DISABLE KEYS | ENABLE KEYS ... (it keeps going!)
More SQL
UPDATE mugs SET price=15 WHERE id = 1 UPDATE mugs SET Oops! D description='hello, world' on't do this! DELETE FROM mugs WHERE id = 42 Try it yourself
67 68
Multiple tables
And you thought it was complicated enough! mugs table: description, id, color but color is an int colors table: name, id Want list of mugs and their colors
69
Problem: Combine data from two tables Attempted Solution: SELECT mugs.description AS name, colors.name AS color FROM mugs, colors Does this work?
70
Wrong answer!
+------+---------+ | desc | color | +------+---------+ | DEC | Blue | | Sun | Blue | | DEC | White | | Sun | White | +------+---------+ What happened?
71
Analysis
A subset is shown here for simplicity.... MySQL followed instructions.
+------+---------+ | desc | color | +------+---------+ | DEC | Blue | | Sun | Blue | | DEC | White | | Sun | White | +------+---------+
SELECT mugs.description AS name, colors.name AS color FROM mugs, colors Got all combinations of mugs and colors!
72
The Fix
What didnt we specify?
SQL functions
SELECT 1 + 2 SELECT MAX (price) FROM mugs MAX is an "aggregate" function also COUNT SELECT name FROM users WHERE age < 18 OR age > 65 SELECT name FROM users WHERE name LIKE Mi%e%"
74
SELECT mugs.description AS name, colors.name AS color FROM mugs, colors WHERE mugs.color = colors.id
73
User accounts
Have a users table. Store passwords. No! Use sha1!
MySQL interface
New! Need PHP 5, MySQL 4.1 Object-oriented The plan: 1. Close anything you open 2. Open connection 3. Do query 4. Use results
75
76
Using results
<TABLE> <?php $mysqli = new mysqli ("localhost", "josti#", "inter", "josti#"); if (mysqli_connect_errno()) echo "connect error!"; $result = $mysqli->query("SELECT * FROM mugs"); while ($row = $result->fetch_assoc()) { echo "<TR><TD>$row[description]</TD> <TD> $row[price]</TD></TR>"; } ?> </TABLE>
77
Secret Forms
Scenario: How do you buy a mug? Want "buy" link on entry... but link, not form Need to hide data in link GET to the rescue!
(never seen GET in a cape and tights?)
78