Creating Databases Uploading Files. Reading & writing files. Homework: Starting planning ‘original’ project.

Slides:



Advertisements
Similar presentations
PHP Form and File Handling
Advertisements

JQuery MessageBoard. Lets use jQuery and AJAX in combination with a database to update and retrieve information without refreshing the page. Here we will.
PHP I.
PHP File Upload ISYS 475.
UFCE8V-20-3 Information Systems Development 3 (SHAPE HK) Lecture 3 PHP (2) : Functions, User Defined Functions & Environment Variables.
Lecture 6/2/12. Forms and PHP The PHP $_GET and $_POST variables are used to retrieve information from forms, like user input When dealing with HTML forms.
1 Chapter 5 – Handling HTML Controls in Web Pages spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science.
PHP (2) – Functions, Arrays, Databases, and sessions.
HTML Form Processing Learning Web Design – Chapter 9, pp Squirrel Book – Chapter 11, pp
Uploading Files. Why? By giving a user the option to upload a file you are creating an interactive page You can enable users have a greater web experience.
Creating Databases applications for the Web Reprise. Basic HTML review, forms Preview: Server side vs client side Classwork: create HTML forms and check.
August Chapter 1 - Essential PHP spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science and Technology.
Creating Databases for Web Applications Posting due by next class on project! Lab: using files & work session Class: asp Application object 3-tier, separating.
PHP Tutorials 02 Olarik Surinta Management Information System Faculty of Informatics.
INTERNET APPLICATION DEVELOPMENT For More visit:
Creating databases for web applications
Lecture 7 Interaction. Topics Implementing data flows An internet solution Transactions in MySQL 4-tier systems – business rule/presentation separation.
Creating databases for web applications SQL. Systems design. ER diagrams. Data flow diagrams. Storyboards. Homework: Plan database and applications for.
Creating databases for web applications Play quizzes Testing process regular expressions: form validation PHP coding handling forms Homework: regular expressions.
1 PHP and MySQL. 2 Topics  Querying Data with PHP  User-Driven Querying  Writing Data with PHP and MySQL PHP and MySQL.
SHOPPING CARTS CHAPTER 19. E-COMMERCE Typically, an e-commerce site will have public pages and admin pages.
PHP meets MySQL.
Creating Databases for Web Applications cookie examples lab time: favorites cookies & Sessions class time for group work/questions on projects Next class:
Chapter 8 Cookies And Security JavaScript, Third Edition.
_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition1  Wiley and the.
Week seven CIT 354 Internet II. 2 Objectives Database_Driven User Authentication Using Cookies Session Basics Summary Homework and Project 2.
PHP1-1 PHP Lecture 2 Xingquan (Hill) Zhu
Lecture 8 – Cookies & Sessions SFDV3011 – Advanced Web Development 1.
Extending HTML CPSC 120 Principles of Computer Science April 9, 2012.
Mr. Justin “JET” Turner CSCI 3000 – Fall 2015 CRN Section A – TR 9:30-10:45 CRN – Section B – TR 5:30-6:45.
1 Chapter 9 – Cookies, Sessions, FTP, and More spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science.
ITCS373: Internet Technology Lecture 5: More HTML.
Variables and ConstantstMyn1 Variables and Constants PHP stands for: ”PHP: Hypertext Preprocessor”, and it is a server-side programming language. Special.
CSC 2720 Building Web Applications Server-side Scripting with PHP.
Creating databases for Web Applications php basics. ing. phpMyAdmin to set up MySQL. Homework: Use phpMyAdmin. Make posting with [unique] source on.
Creating PHPs to Insert, Update, and Delete Data CS 320.
Creating Databases Local storage. join & split Classwork: show 1 table application. Share designs for oscars application. Adaptive select. Homework: [Catch.
Creating Databases applications for the Web Basic HTML review, forms Preview: Server side vs client side Flash HW: Review HTML forms and FLASH examples.
Creating databases for web applications Library. New example: student database. Homework: Complete class example. Catch up on source postings. Do creation.
Cookies and Sessions IDIA 618 Fall 2014 Bridget M. Blodgett.
1 Web Servers (Chapter 21 – Pages( ) Outline 21.1 Introduction 21.2 HTTP Request Types 21.3 System Architecture.
 Registry itself is easy and straightforward in implementation  The objects of registry are actually complicated to store and manage  Objects of Registry.
>> PHP: Insert Query & Form Processing. Insert Query Step 1: Define Form Variables Step 2: Make DB Connection Step 3: Error Handling Step 4: Define the.
NMD202 Web Scripting Week5. What we will cover today PHP & MySQL Displaying Dynamic Pages Exercises Modifying Data PHP Exercises Assignment 1.
Creating a simple database This shows you how to set up a database using PHPMyAdmin (installed with WAMP)
Creating Databases for Web applications Server side vs client side PHP basics Homework: Get your own versions of sending working: both html and Flash!
Creating Databases for Web applications SQL. XML. Linked Lists. NoSQL. Homework: Keep working on projects. Post constructive feedback on other projects.
©SoftMooreSlide 1 Introduction to HTML: Forms ©SoftMooreSlide 2 Forms Forms provide a simple mechanism for collecting user data and submitting it to.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
SESSIONS 27/2/12 Lecture 8. ? Operator Similar to the if statement but returns a value derived from one of two expressions by a colon. Syntax: (expression)
Creating Databases for Web Applications 3-Tier. Design vs Function vs Content. More SQL. More php. Homework: work on final projects.
Since you’ll need a place for the user to enter a search query. Every form must have these basic components: – The submission type defined with the method.
Class 3Intro to Databases Class 4 Simple Example of a Database We’re going to build a simple example of a database, which will allow us to register users.
PHP and Sessions. Session – a general definition The GENERAL definition of a session in the “COMPUTER WORLD” is: The interactions (requests and responses)
ASSIGNMENT 2 Salim Malakouti. Ticketing Website  User submits tickets  Admins answer tickets or take appropriate actions.
ITM © Port,Kazman 1 ITM 352 Cookies. ITM © Port,Kazman 2 Problem… r How do you identify a particular user when they visit your site (or any.
NMD202 Web Scripting Week2. Web site
Dr. Abdullah Almutairi Spring PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages. PHP is a widely-used,
CGS 3066: Web Programming and Design Spring 2016 PHP.
PHP: Further Skills 02 By Trevor Adams. Topics covered Persistence What is it? Why do we need it? Basic Persistence Hidden form fields Query strings Cookies.
Radoslav Georgiev Telerik Corporation
Creating Databases for Web applications
Confirm teams. Review of diagrams. SELECT problems.
Introduction to Dynamic Web Programming
Creating Databases Local storage. join & split
Creating Databases Catch up presentations. Reading & writing files. Sessions. Homework: Starting planning ‘original’ project.
ITM 352 Cookies.
Cookies BIS1523 – Lecture 23.
Web Systems Development (CSC-215)
Mr. Justin “JET” Turner CSCI 3000 – Fall 2016 Section DA MW 4:05-5:20
Presentation transcript:

Creating Databases Uploading Files. Reading & writing files. Homework: Starting planning ‘original’ project.

Uploading files using php What if you have an application, such as origami store, video portal, etc., and you want to provide a way for users to upload files to the server? – Users may be other people in same organization. – Now, users are not that trustworthy OR skilled, so need to put in checks!!! – Some php installations may not allow this at all. CTS was reluctant. Why?

Example eyer/fileupload1.html eyer/fileupload1.html – HTML does much of the work for us: a special type of input plus special attributes in the form tag. This invokes fileupload2.php and stores image files under a certain size in the subfolder uploads

fileupload1.html Get file name Upload image file: <form action="fileupload2.php" method="post" enctype="multipart/form-data"> Filename:

fileupload2.php My code displays more information that you would want in a production system!!! You would want the checking. Information on the uploaded files are in a php variable calls $_FILES. The uploaded files are in a temporary directory. My code moves it into a subfolder of the folder of the current script. CTS may have made special permissions for this to work.

<?php echo "Script path is $basename "; echo "File type is ". $_FILES["ufile"]["type"]. " "; echo "File size is ". $_FILES["ufile"]["size"]. " " ; if ((($_FILES["ufile"]["type"] == "image/gif") || ($_FILES["ufile"]["type"] == "image/jpeg") || ($_FILES["ufile"]["type"] == "image/pjpeg")) && ($_FILES["ufile"]["size"] < )) {

if ($_FILES["ufile"]["error"] > 0) { echo "Return Code: ". $_FILES["ufile"]["error"]. " "; } else { echo "Upload: ". $_FILES["ufile"]["name"]. " "; echo "Type: ". $_FILES["ufile"]["type"]. " "; echo "Size: ". ($_FILES["ufile"]["size"] / 1024). " Kb "; echo "Temp file: ". $_FILES["ufile"]["tmp_name"]. " "; if (file_exists($_FILES["ufile"]["name"])) { echo $_FILES["ufile"]["name"]. " already exists. "; } else { $target = "uploads/". $_FILES["ufile"]["name"] ; echo "The length of $target is ". strlen($target). " "; move_uploaded_file($_FILES["ufile"]["tmp_name"],$target); echo "Stored as: ". $target; } } } else { echo "Invalid file"; } ?>

Files Before there were databases, there were simple files. What about using a file for data? Example application: top best scores. Only keep top 5 scores. My demonstration application: res.html res.html [Simply] requests a player name and a score. Adds to file if big enough. to mask error. Note: closes file and may or may not re-open. Script displays more than appropriate for production version.

bestscores.html Input new scores Player Score

Note The score input is a piece of text. Some browsers may check that that text represents a number, but it is still text. My script will create a scores.txt file if one does not already exist in the subfolder uploads. My script has debugging messages that should be removed for a production system.

strategy Open [connection to] file for reading. Read in the whole file (5 records) into an array variable $data. Close the connection to the file. Each record is name,score – Use explode to get the two different things. – Convert the score to a number – Produce an array $scores of numbers. Compare intval($newscore) to elements in $scores. – Find the first one smaller than the proposed new score. Manipulate $data by inserting a record holding “$newname,$newscore\n” Open [connection to] file for writing. For php, writing means erasing whole file and then re-writing it. Write out $data items as records.

bestscores.php Best scores <?php $newname = $_GET['player']; $newscore = $_GET['score']; $filen = "uploads/scores.txt"; $open = fopen($filen,"r"); print (" Just tried to open file to add $newname and $newscore. "); print ("returned handler is $open "); if ($open) { $data = file($filen); fclose($open); //file closed for ($i=0;$i<count($data);$i++) { $item = explode(",",$data[$i]); $score = intval($item[1]); $scores[] = $score; print ("current score: $i ".$item[0]." ".$item[1]." "); }

for($i=0;$i<count($scores);$i++) { if (intval($newscore)>$scores[$i]) { $olddata = $data[$i]; $data[$i] = "$newname,$newscore\n"; for ($j=$i+1;$j<count($scores);$j++) { $nextone = $data[$j]; $data[$j] = $olddata; $olddata = $nextone; } // $j for break; //leave $i for loop } // if newscore better } // $i loop

print ("now will write out new data array. "); for($i=0;$i<count($scores);$i++) { print($data[$i]." "); } // now close the file which was open for print (" Trying to open $filen for writing "); $open = fopen($filen,"w");

if ($open) { print("writing out to file "); for($i=0;$i<count($scores);$i++) { fwrite($open,$data[$i]); } fclose($open); } else { print (" Unable to write updated file. The returned handler value was $open. "); } } // file opened successfully for initial read

else { // need to create //may not be necessary since file wasn't opened. print ("scores file doesn't exist yet "); $open = fopen($filen,"w"); if ($open) { $setsize = 5; //keep 5 top scores fwrite($open,"$newname,$newscore\n"); for ($i=1;$i<$setsize;$i++) { fwrite($open,"X,0\n"); } else { print ("couldn't create scores file."); } } //needed to create scores file ?>

Application Store results of a "test" with one file / person file name based on "code" – Presented as input type=password, but more just identifier If person takes test more than once, add on to the file. – This can produce many files! eyer/testquiz.html eyer/testquiz.html

testquiz.html function check() { var oksofar = true; if (!((document.f.a1.value.length>0) && (document.f.a2.value.length>0) && (document.f.a3.value.length))){ alert("please submit answer for each question"); oksofar = false; } if (document.f.code.value.length<3){ alert ("The identifying code must be at least 3 characters long"); oksofar = false; } if (oksofar) { return true;} else { return false; } }

body of testquiz Sample quiz Identifying code: Answer 1: Answer 2: Answer 3:

from storeanswers.php <?php $code = $_POST['code']; $a1 = $_POST['a1']; $a2 = $_POST['a2']; $a3 = $_POST['a3']; $nowp= new DateTime(); $now = $nowp->format('Y-m-d H:i:s'); $answers = "$code $now answers are 1= $a1 2= $a1 3= $a3 ".PHP_EOL; $filen ="uploads/answers". $code. ".txt" ; $open=fopen($filen,"a"); if ($open) { fwrite($open,$answers); fclose($open); print "Answers stored "; } else { print "Problem with storing answers"; } ?>

sample output: done twice, producing 2 lines jmm :54:54 answers are 1= 23 2= 23 3= 4 jmm :55:09 answers are 1= 20 2= 20 3= 6

More on files Create a subfolder in the folder/directory where you php file is: call it uploads. Consult with CTS to confirm you can do this. – May need their help to set permissions

Why use files Very simple structure OR more complex or just different from tables – Perhaps with links (pointers) such as family or corporate tree – ?

Refrain on 3 tier Some divide the html tier into content versus style, with CSS holding the style. This is the interaction tier. – Note: Flash and other languages (Processing, Java, ??) also do more function Middle tier, php, do 'business logic', other function. Information tier, MySQL, holds information! – Serves multiple functions. Implemented (possibly) by different groups in an enterprise.

Another tier? or is the 3 tier terminology insufficient Organizations use code and content developed and maintained by others. – Web services – cloud computing – content such as Google maps – ??? Extra credit opportunity to report / comment.

php to php Alternative to cookies or data passed via query strings are Sessions. The sessions may be passed via the HTTP headers – Extra credit opportunity: research and do posting on php Sessions Access and set using $_SESSION. This, like $_COOKIE, etc. is an associative array: accessed using names not indices. – NOTE: the shopping cart in my store application is stored as a Session variable and is itself an associative array.

<?php session_start(); if (!isset($_SESSION["cart"])) { $_SESSION['cart']=array(); $_SESSION['items'] = 0; $_SESSION['totalprice']=0.00; $cart = array(); } else { //print ("cart already started "); $cart = $_SESSION['cart']; } ?>

Shopping Cart <? require("displaycartfunction.php"); ?> <?php require("opendbo.php"); ?> Shopping cart <? if (isset($_GET['productid'])) { $p_id = $_GET['productid']; $quantity=$_GET['quantity']; $cart[$p_id] = $quantity; $_SESSION['cart'] = $cart; }

displaycart(); ?> Checkout (submit order)! More shopping!

displaycart Function stored in file displaycartfunction. Assumes that connection has been made and session started. Makes use of the foreach construction for associative arrays. – Since associative arrays don't use index values 0 to length of array, what is the code to examine each element? Answer: foreach($aa as $key=>$qty) { } assuming $aa is the associative array and $key and $qty are variables used in the loop for the keys and values – Makes use of number_format($totalprice,2) to produce dollars and cents

<?php //assumes that opendbo called, and session started //when call is made. function displaycart() { global $cart, $DBname, $link, $totalprice; print (" "); print (" Product ID Product Name Quantity Total cost "); $items = 0; //note session variable items not used $totalprice = 0.00; $cart = $_SESSION['cart'];

foreach as $pid => $qty) { $items += $qty; //print(" the pid is ".$pid. " and the qty is ". $qty); $query="Select * from catalog where id='$pid'"; //print("query is $query"); $result = mysql_db_query($DBname, $query, $link); $item_price = mysql_result($result,0,"cost"); $item_name = mysql_result($result,0,"p_name"); $item_total_price = $item_price * $qty; $totalprice += $item_total_price; $item_total_pricef = number_format($item_total_price,2); print (" $pid $item_name $qty $item_total_pricef "); }

$totalpricef = "$". number_format($totalprice,2); print(" TOTALS $items items $totalpricef "); $_SESSION['items']=$items; $_SESSION['totalprice']=$totalprice; } ?>

Project assignment Design and develop your own database php project – work individually and then gather team to determine general idea Make posting to moodle with idea and names of people on team YOU MAY WORK BY YOURSELF or in small group. From more, more is expected. – Develop database design (ER diagram) and Data flow diagram Presentations on 4/20 – Complete project Presentations on 5/11

Minimal requirements At least 2 tables and at least 2 SQL statements make use of at least one of – localStorage – file(s) – file uploading – sending At least 2 types of agents. For example: setup and production use. Error handling (form input validation)

Classwork / homework More postings (mainly from those people who haven’t done it) on security, passwords, normalization, and other topics). Think about ‘original / from scratch’ project. Think about your teams. – Maybe smaller? – It is okay to ‘double-dip’; for example, build on project done for another class or you anticipate doing by adding a database. Make proposal to moodle forum – Topic, names of people on team

Planning presentation Tell what your project is Show ER diagram – Definition of the tables Show DFD – Definition of the tasks and the agents (aka users) and the data stores (database, maybe tables, maybe localStorage) If you have it, perhaps a form This is a presentation of plans!!!!!!