24
Web Scripting Web Scripting [PHP] [PHP] CIS166AE CIS166AE Wednesdays 6:00pm – Wednesdays 6:00pm – 9:50pm 9:50pm Rob Loy Rob Loy

Web Scripting [PHP] CIS166AE Wednesdays 6:00pm – 9:50pm Rob Loy

Embed Size (px)

Citation preview

Web Scripting [PHP]Web Scripting [PHP]CIS166AECIS166AE

Wednesdays 6:00pm – 9:50pmWednesdays 6:00pm – 9:50pm

Rob LoyRob Loy

AgendaAgenda

Homework/Lab ReviewHomework/Lab Review PresentationsPresentations SQL UpdateSQL Update Creating SQL TablesCreating SQL Tables ValidationValidation Mid-term ProjectMid-term Project

Database InfrastructureDatabase Infrastructure

User

ClientWeb

Cloud

DB

RecordRecordRecordRecord

TableTableTableTable

DatabaseDatabaseDatabaseDatabase

IMPORTANT NOTEIMPORTANT NOTE

A Database Server can not A Database Server can not have a DB with the same have a DB with the same name. Since we use ONE name. Since we use ONE DB Server, all our DBs have DB Server, all our DBs have to have unique names.to have unique names.

Information needed for DBInformation needed for DB

Need server name/IP Need server name/IP (e.g. mysql.<domainname>.com or (e.g. mysql.<domainname>.com or localhost)localhost)

Need usernameNeed username Need passwordNeed password Need DB nameNeed DB name Need table namesNeed table names Need column namesNeed column names

IMPORTANT NOTEIMPORTANT NOTE

SQL Commands (SQL Commands (SELECTSELECT, , INSERTINSERT, , UPDATEUPDATE, etc) are almost always , etc) are almost always

written in CAPS and other pieces of a written in CAPS and other pieces of a SQL statement are written as normal SQL statement are written as normal

case.case.

IMPORTANT NOTEIMPORTANT NOTE

Never do a Never do a DELETEDELETE statement, statement, instead “archive” the date.instead “archive” the date.

PHP / mySQL SyntaxPHP / mySQL Syntax// Connect to server// Connect to server$con = mysql_connect(“SERVER",“USER",“PASSWORD");$con = mysql_connect(“SERVER",“USER",“PASSWORD");// Connect to DB// Connect to DBmysql_select_db(“DATABASE", $con);mysql_select_db(“DATABASE", $con);// Execute SQL Query// Execute SQL Query$result = mysql_query("SELECT * FROM TABLE");$result = mysql_query("SELECT * FROM TABLE");// The RECORDSET will be an object (e.g. $result)// The RECORDSET will be an object (e.g. $result)// Need to break the object into an array (e.g. $row)// Need to break the object into an array (e.g. $row)while($row = mysql_fetch_assoc($result))while($row = mysql_fetch_assoc($result)){{// The WHILE runs until END OF RECORD// The WHILE runs until END OF RECORDecho $row['FirstName'] . " " . $row['LastName‘] ."<br/>";echo $row['FirstName'] . " " . $row['LastName‘] ."<br/>";}} // Close connection// Close connectionmysql_close($con);mysql_close($con);

http://www.w3schools.com/PHP/php_mysql_connect.asp

Connecting to your DBConnecting to your DB

Server: mysql.<domainname>.comServer: mysql.<domainname>.com Username: sccstudent_<id>Username: sccstudent_<id> Password: Maricopa_<id>Password: Maricopa_<id> DB name: sccstudent_<id>DB name: sccstudent_<id> ------------------------------------------------------------------------------------------ Table: week4Table: week4 Columns: id, username, password, firstname, Columns: id, username, password, firstname,

lastname, phone, email, createdlastname, phone, email, created

PHP / SQL Update StepsPHP / SQL Update Steps

SELECT statement to pull ONE recordSELECT statement to pull ONE recordSELECT * FROM persons WHERE id = 1;SELECT * FROM persons WHERE id = 1;

Use the result from step one to populate the Use the result from step one to populate the HTML form fieldsHTML form fields<input name=“first” value=“<?php echo $fname; ?>” /><input name=“first” value=“<?php echo $fname; ?>” />

After user submits, take value and UPDATE the After user submits, take value and UPDATE the tabletableUPDATE person SET fname=”$_POST[“first”]” WHERE id=1;UPDATE person SET fname=”$_POST[“first”]” WHERE id=1;

Form Data ValidationForm Data Validation

Client side: JavascriptClient side: Javascript Make sure information is filled out BEFORE sending to the server.Make sure information is filled out BEFORE sending to the server. Saves unnecessary traffic.Saves unnecessary traffic. Maintains user entry seamlessly.Maintains user entry seamlessly.

Sever side: PHPSever side: PHP Users can disable Javascript.Users can disable Javascript. Content can be created maliciously access/update the DB.Content can be created maliciously access/update the DB. More control closer to the SQL statement.More control closer to the SQL statement.

Validation TestValidation Test

Is Null or EmptyIs Null or Empty Type text vs. numericType text vs. numeric Is an email address, phone, social security, etc.Is an email address, phone, social security, etc. Limited number of charactersLimited number of characters HTML codeHTML code Special charactersSpecial characters Malicious code (e.g. WHERE 1=1)Malicious code (e.g. WHERE 1=1)

JavaScript ValidationJavaScript Validation function fValid(){function fValid(){

var x=document.forms[“form1"][“first"].value;var x=document.forms[“form1"][“first"].value;if (x==null || x=="")if (x==null || x=="")  {  {

alert("First name must be filled out");alert("First name must be filled out");    return false;return false;  }  }} }

<form name=“form1" action=“page.php" <form name=“form1" action=“page.php" onsubmit="return fValid()" method="post">onsubmit="return fValid()" method="post">

<p>First: <input type="text" name=“first"><p>First: <input type="text" name=“first"><p><input type="submit"><p><input type="submit">

</form></form>

http://www.w3schools.com/js/js_form_validation.asp

IMPORTANT NOTEIMPORTANT NOTE

The life cycle in PHP is the The life cycle in PHP is the length of time it takes the length of time it takes the server to find the file, process server to find the file, process the information, and send the the information, and send the completed static HTMLcompleted static HTML back to the client. back to the client.

Sort DB recordsSort DB records SELECT * FROM persons ORDER BY fname ASC;SELECT * FROM persons ORDER BY fname ASC; SELECT * FROM persons ORDER BY fname DESC;SELECT * FROM persons ORDER BY fname DESC;

The ORDER BY keyword is used to sort the The ORDER BY keyword is used to sort the result-set by a specified column.result-set by a specified column.

The ORDER BY keyword sort the records in The ORDER BY keyword sort the records in ascending order by default.ascending order by default.

If you want to sort the records in a descending If you want to sort the records in a descending order, you can use the DESC keyword.order, you can use the DESC keyword.

http://www.w3schools.com/sql/sql_orderby.asp

phpMyAdminphpMyAdmin

mySQL Data TypesmySQL Data Types

NumericNumeric FloatFloat IntegerInteger

StringString CharChar VarcharVarchar

DateDate

http://dev.mysql.com/doc/refman/5.0/en/data-types.html

Create a new mySQL TableCreate a new mySQL Table

Log into the phpmyadmin siteLog into the phpmyadmin site Select a DB from right columnSelect a DB from right column Create a table name and pick number of columnsCreate a table name and pick number of columns

Create mySQL Table StructureCreate mySQL Table Structure Name each fieldName each field

Select a TypeSelect a Type

Assign a length for VARCHAR or CHAR typesAssign a length for VARCHAR or CHAR types

Design default valuesDesign default values

Determine if NULL values allowed by using NULL Determine if NULL values allowed by using NULL checkboxcheckbox

Pick one field as ID and select INT type and A_I Pick one field as ID and select INT type and A_I checkboxcheckbox

phpmyadmin screenphpmyadmin screen

In classIn class

Update SQL DBUpdate SQL DB Sort SQL RecordsetsSort SQL Recordsets Create TableCreate Table

Questions?Questions?

LabLab

Display the “create” field from the table Display the “create” field from the table Update the form to allow the user to modify Update the form to allow the user to modify

firstname, lastname, phone, and email addressfirstname, lastname, phone, and email address Add sort by lastname (sort for firstname from Add sort by lastname (sort for firstname from

class should also work)class should also work) Send email to Send email to [email protected] with URL to input with URL to input

form file before 6pm on form file before 6pm on October 12October 12..

Mid-term ProjectMid-term Project

Create mySQL table that has at least 5 fields Create mySQL table that has at least 5 fields One field should be ID with Auto IncrementOne field should be ID with Auto Increment Display all records from the tableDisplay all records from the table Create a web form that has INSERT and Create a web form that has INSERT and

UPDATE functionality for the tableUPDATE functionality for the table Add a sort functionalityAdd a sort functionality At least 2 have to be required and display error At least 2 have to be required and display error

messages where appropriatemessages where appropriate Send email to Send email to [email protected] with URL with URL

to input form file before 6pm on to input form file before 6pm on October 19October 19..