Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.



Published on

Published in: Technology
  • Be the first to comment

  • Be the first to like this


  1. 1. Topeka, KS - High school sophomore Brett Tyson was suspended today after teachers learned he may be using PHP. "A teacher overheard him say that he was using PHP, and as part of our Zero-Tolerance PHP and MySQL 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 Tutorial 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." Michael Coblenz 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, 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 1 2 Introductions The Metadata 2 parts, each 3 hours Me PHP first, MySQL second You End at lunch today Continue tomorrow 3 4 The Rules Why are we here? Think before you code! Want sites that change - dynamic sites. Don’t just copy code from here Need more power! No wimps! Powerful sites need powerful tools This class is hardcore The tool makes the developer Don’t get lost! Questions are required, not optional 5 6
  2. 2. Our Example Static vs. Dynamic Sites Static: stays the same Might be edited periodically An online store! Dynamic: changes on demand search, change preferences, interact, post, edit 7 8 What is PHP? Why a database? Software package Need to store lots of data! Fast access to data Works with web server software Data must persist Similar to: ASP, ColdFusion, Java Server Pages (JSP) Data is structured 9 10 How Static Pages Work How Dynamic Pages Work Hard Drive HTTP server (e.g. Apache, IIS) SQL query PHP "Please process MySQL "Here is an HTML file index.php." query for index.php." result Database server (maybe HTTP request: I want index.html. GET index.html HTTP server (Apache) index.html I want index.php. GET index.php User’s computer User’s computer 11 12
  3. 3. The Plan Down to business! PHP today MySQL today/tomorrow Integration tomorrow Let’s learn PHP! Project: online store! tomorrow 13 14 Really: What is PHP? PHP Language Intro PHP: Hypertext Preprocessor Think: "I’m generating an HTML file." Program to help server Two categories: 1. Run script (a program!) PHP code Generate HTML HTML 2. Send HTML to HTTP server HTML gets sent to user directly 3. HTTP server sends HTML to user PHP code executed, output sent to user 15 16 Which witch is which? Statements Code in PHP code consists of statements Delimiters: Courier Semicolon-terminated <?php Exception: last statement ?> <?php Between delimiters: MUST be PHP code echo ("Hello, world!"); doStuff (); Not between delimiters: MUST be HTML echo ("Goodbye, world!"); ?> 17 18
  4. 4. Delimiter Examples Hello, world! Input Output A working example Put this in hello.php in Sites folder <?php printPi(); ?> 3.14159265359… <HTML><HEAD> printPi(); printPi(); <TITLE>Hello!</TITLE></HEAD> <BODY> <?php echo(40 + 2); ?> 42 <?php echo ("Hello, world!");?> </BODY></HTML> 40 + 2 40 + 2 Look at <server>/~josti#/hello.php 19 20 Spot the syntax errors Variables < ?php echo ("hi") ?> Name preceded by $ <?php echo (hi) ?> No declarations, very weak typing <?php echo ("hi") Must begin with letter or underscore echo ("hi") ?> Names contain only letters, numbers, underscores <?php echo (""hello!""); ?> $name = "George"; use instead: WARNING: undefined variables have NULL <?php echo (""hello!""); ?> value; can use without error! 21 22 Comments If statements if ($grade > 64) { Comment your code! echo ("You passed!"); Code is for people, not machines. } else { PHP does this; // ignores this echo ("What a loser!"); /* PHP ignores } Curly braces only required for more than one all of this */ statement 23 24
  5. 5. More tests Handy Boolean operators Greater than > Not ! if ($grade >= 64 && !($grade > 75)) Less than < echo "lucky punk!"; And && Greater than or equal to >= if (calculateMeaningOfLife() == 42) Less than or equal to <= echo "Phew!"; Or || Not equal <> 25 26 Not syntax errors... Spot the errors Loops or "What does this code do?" for ($i = 0; $i < $max; $i++) if (name == "Dave") echo "D"; { if ($name = "Dave") echo "D"; echo ("iteration " . $i); } if ($foo < 6); echo "less!"; Notice the "." - it’s the string concatenation operator. if (1 < 4) while (isMoreData()) { if (5 > 42) echo "one"; printData(); else echo "two"; } 27 28 Exercise Functions to Know & Tell die("You lose! No data Create a web page that displays your name 500 times. for you!"); mail($toAddress,$subject, use a for loop. $message, $headers); After that works, modify it to also print a line number on isset($variable); each line. But how do I read the documentation? We'll see later. 29 30
  6. 6. Arrays Tables refresher (HTML) Actually ordered maps <TABLE BORDER="1"> <TR> keys (strings or ints) to values (stuff in <TD>100</TD> array) <TD>200</TD> <TD>300</TD> $arr = array (5 => 1); </TR> <TR> echo $arr[5]; // 1 <TD>400</TD> <TD>500</TD> $arr["x"] = 42; remember this for MySQL <TD>600</TD> </TR> echo $arr["x"]; // 42 </TABLE> 31 32 Generating tables Questions? <TABLE> <?php $rows = 10; $cols = 3; for ($i = 0; $i < $rows; $i++) { echo "<TR>"; for ($j=0; $j < $cols; $j++) { Next up: Form processing echo "<TD>row $i,col $j</TD>"; } echo "</TR>"; } ?> </TABLE> 33 34 Forms The Form <FORM action="processor.php" method="post"> <INPUT type="text" name="username" Two parts size="20"/> form (HTML) <INPUT type="password" name="password" size="20"/> form processor (PHP) <INPUT type="submit" value="click here!"/> </FORM> 35 36
  7. 7. The form processor <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> Input fields are variables (PHP magic!) Method: how browser sends data use $_POST["variable"] if sent with post. GET $_GET["variable"] for get. POST Changed in PHP 4.2 for security. Action: where browser sends data Do whatever is appropriate with them. INPUT: a field for data entry Query a database, perhaps? Can be the same file as the form 37 38 A simple login system Exercise <?php if ($_POST["username"] == "teacher" && $_POST["password"] == "goldfish") { echo ("Here are the grades."); Make a form for users to enter their name and favorite color. } If their favorite color is the same as yours, print something else { echo ("You lose!"); special. } ?> 39 40 One page forms PHP include/require <?php if (isset($_POST["username"])): Avoid code duplication echo ("Hello, $_POST[username]"); include ("header.php"); else: ?> require ("login.php"); <FORM ...>....</FORM> Notice the colons! Same, but require fails if its arguments doesn’t exist. <?php endif; ?> Avoids ugly echos. 41 42
  8. 8. Handling login Cookies Or: angering ignorant users in one easy step! Save a little data on user’s machine Problem: each page wants $username, $password. Like, say, the username, once they authenticated. Solutions? setcookie ("username", $username); Yes, you. Be more careful if you care about security. 43 44 How can login work? require ("login.php"); in login.php: if username not set, ask and die. On to MySQL! That’s it! Not very secure. There are better ways. 45 46 What is SQL? What is MySQL? Structured Query Language Particular implementation of SQL Not English, Spanish, French,... Others: Query: request SQLite (included in PHP 5) "Please add Joe to the user list." PostgreSQL "Who posted today?" MS SQL Server 47 48
  9. 9. MySQL includes... Relational Databases mysqld Daemon - runs all the time Server process Manages files that contain actual database Not your mother’s databases! Database == spreadsheet? mysql Client - runs when you need it Talks to mysqld 49 50 A good database? A Better Database Mug Color Price ID Color ID Mug Price Color Apple White $10 0 Apple 10 0 0 White Microsoft Black $2 1 Microsoft 2 1 1 Black Sun Green $5 2 Sun 5 2 2 Green DEC green $100 3 DEC 100 2 Colors Mugs 51 52 Relational Databases Buzzwords Table: Spreadsheet Avoid Duplication Database: Collection of tables Assign a UNIQUE ID to each row Row or record: Entry in table Refer to data in other tables by ID Column: Field for entering data Unambiguous! Schema: A particular database setup 53 54
  10. 10. Types Some data types INT: -2147483648 to 2147483647 Think "kinds" FLOAT, DOUBLE Types of tools: hammer, screwdriver DATE, TIMESTAMP bang (hammer)? OK. VARCHAR(20): up to 20 characters turn (screwdriver)? OK. TEXT: up to 65,535 characters turn (hammer)? No! BLOB: like TEXT, but sorting is case insensitive 55 56 Your turn! Using MySQL Design a database schema for a store for your mug collection. Use mysql client to talk to server Hint: ssh (with PuTTY). See blackboard. mugs table Login: josti#. Password: international users table (better record who bought what!) mysql -u josti# -p What data do you need? Now: only type MySQL commands. Groups of three 57 58 MySQL commands CREATE TABLE mugs (id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY (ID), description VARCHAR(40), use josti#; price float); End commands with semicolons Pattern: create table <table_name> (column Case InSenSiTiVe definition, column definition, ...) show tables; Column definition: <column_name> <type> 59 60
  11. 11. Changing table schemata Indices and Keys Index: pre-sort by this, so searching is MUCH faster ALTER TABLE mugs ADD quantity Primary key: unique identifier int Constraints are your friend! NOT NULL, DEFAULT 61 62 Adding Data Getting data INSERT INTO mugs You SELECT the data you want FROM the table it's in. (description, price) SELECT description, price FROM values ('DEC', 100); mugs or: INSERT INTO mugs SET SELECT description FROM mugs description='DEC', ORDER BY description ASCENDING price=100; SELECT description FROM mugs Add a few records of your own! WHERE price < 10 63 64 A brief syntax interlude INSERT [LOW_PRIORITY | DELAYED] [IGNORE] [INTO] tbl_name [(col_name,...)] VALUES ({expr | "In the beginning there was the word. But by the time the DEFAULT},...),(...),... second was added to it, there was trouble. For with it came [ ON DUPLICATE KEY UPDATE syntax..." —John Simon col_name=expr, ... ] "Colorless green ideas sleep furiously." - Noam Chomsky [stuff]: stuff is optional Let’s look at the manual. {a | b}: pick a or b, not both. Must have one. 65 66
  12. 12. ALTER [IGNORE] TABLE tbl_name alter_specification [, alter_specification] ... alter_specification: More SQL 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,...) UPDATE mugs SET price=15 | ADD [CONSTRAINT [symbol]] UNIQUE [index_name] [index_type] (index_col_name,...) WHERE id = 1 | ADD [FULLTEXT|SPATIAL] [index_name] (index_col_name,...) | ADD [CONSTRAINT [symbol]] FOREIGN KEY [index_name] UPDATE mugs SET (index_col_name,...) [reference_definition] Oops! D | ALTER [COLUMN] col_name {SET DEFAULT literal | DROP DEFAULT} on't do description='hello, world' | CHANGE [COLUMN] old_col_name column_definition [FIRST|AFTER col_name] this! | MODIFY [COLUMN] column_definition [FIRST | AFTER col_name] | DROP [COLUMN] col_name DELETE FROM mugs WHERE id | DROP PRIMARY KEY | DROP INDEX index_name = 42 | DROP FOREIGN KEY fk_symbol | DISABLE KEYS | ENABLE KEYS ... (it keeps going!) Try it yourself 67 68 Multiple tables mugs: description, id, color colors: name, id Problem: And you thought it was complicated enough! Combine data from two tables mugs table: description, id, color Attempted Solution: but color is an int SELECT mugs.description AS name, AS color colors table: name, id FROM mugs, colors Want list of mugs and their colors Does this work? 69 70 Wrong answer! Analysis +------+---------+ +------+---------+ | desc | color | +------+---------+ | desc | color | | DEC | Blue | | Sun | Blue | +------+---------+ A subset is | DEC | White | | DEC | Blue | shown here MySQL followed instructions. | Sun | White | +------+---------+ | Sun | Blue | for simplicity.... SELECT mugs.description | DEC | White | AS name, AS | Sun | White | color FROM mugs, colors +------+---------+ Got all combinations of mugs and colors! What happened? 71 72
  13. 13. previously: SELECT The Fix mugs.description AS name, AS color FROM mugs, colors SQL functions SELECT 1 + 2 SELECT MAX (price) FROM What didn’t we specify? mugs SELECT mugs.description AS name, MAX is an "aggregate" function AS color also COUNT FROM mugs, colors SELECT name FROM users WHERE mugs.color = WHERE age < 18 OR age > 65 SELECT name FROM users WHERE name LIKE ‘Mi%e%" 73 74 User accounts MySQL interface New! Need PHP 5, MySQL 4.1 Object-oriented Have a users table. The plan: Store passwords. 1. Close anything you open 2. Open connection No! Use sha1! 3. Do query 4. Use results 75 76 Using results Secret Forms <TABLE> <?php $mysqli = new mysqli ("localhost", "josti#", Scenario: How do you buy a mug? "inter", "josti#"); if (mysqli_connect_errno()) Want "buy" link on entry... echo "connect error!"; $result = $mysqli->query("SELECT * FROM mugs"); but link, not form while ($row = $result->fetch_assoc()) { echo "<TR><TD>$row[description]</TD> <TD> Need to hide data in link $row[price]</TD></TR>"; } GET to the rescue! ?> (never seen GET in a cape and tights?) </TABLE> 77 78
  14. 14. Secret forms: the trick! The project: a store! 1. Display all mugs for sale. Need to encode post ID in link 2. Add a "buy" link next to each mug. http://.../showMugs.php?mug=42 1. When clicked: go to a "complete purchase" ...?mug=42&sortBy=date&order=0 page 3. Add an "inventory" field to the mugs table so you Use urlencode($uglyStuff); can track how many are in stock. e.g. "Thing with spaces & stuff" 4. It should subtract one from the inventory every hence ...?foo%20%37bar%20+baz time someone buys one. 5. Starter code is provided. 79 80