Creating databases for web applications Report on using sources, getting examples working. Retrieve information from database. Recordsets. Arrays. Loops.

Slides:



Advertisements
Similar presentations
PRACTICAL PHP AND MYSQL WALKTHROUGH USING SAMPLE CODES – MAX NG.
Advertisements

Concepts of Database Management Sixth Edition
Concepts of Database Management Seventh Edition
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 14 Web Database Programming Using PHP.
Concepts of Database Management Sixth Edition
Microsoft Access 2010 Chapter 7 Using SQL.
1 CS428 Web Engineering Lecture 23 MySQL Basics (PHP - VI)
Introduction To Databases IDIA 618 Fall 2014 Bridget M. Blodgett.
Creating Databases SELECT. UPDATE. Demonstrate projects. Classwork / Homework: Prepare to choose teams & projects.
© Yanbu University College YANBU UNIVERSITY COLLEGE Management Science Department © Yanbu University College Module 6:WEB SERVER AND SERVER SIDE SCRPTING,
Creating databases for web applications
1 Chapter 8 – Working with Databases spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science and Technology.
MySQL in PHP – Page 1 of 17CSCI 2910 – Client/Server-Side Programming CSCI 2910 Client/Server-Side Programming Topic: MySQL in PHP Reading: Williams &
Creating databases for web applications Walk before run? Songs with features example. Retrieve information from database. Recordsets. Arrays. Loops. Homework:
Creating Databases for Web Applications SQL Select extras Listing [names of] tables generalized display of recordset simple password handling php and other.
Microsoft Access 2010 Chapter 7 Using SQL. Change the font or font size for SQL queries Create SQL queries Include fields in SQL queries Include simple.
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 Making a table of SQL queries. PHP and other DBMSs. Rights. Left Join, etc. Homework: Make posting on Open Source.
Creating databases for web applications Play quizzes Testing process regular expressions: form validation PHP coding handling forms Homework: regular expressions.
MySQL + PHP.  Introduction Before you actually start building your database scripts, you must have a database to place information into and read it from.
1 PHP and MySQL. 2 Topics  Querying Data with PHP  User-Driven Querying  Writing Data with PHP and MySQL PHP and MySQL.
Creating Databases Uploading Files. Reading & writing files. Homework: Starting planning ‘original’ project.
Creating Databases for Web Applications Library diagrams Continue with diagrams for video clip archive and for (Flash) grid design. General and specific.
PHP meets MySQL.
Analyzing Data For Effective Decision Making Chapter 3.
Programming Games in Visual Basic: Data base Catch up questions Data base: generalities & specifics on Visual Basic links Lab: work on projects.
Creating Databases More SQL. Design. Original Project Assignment Homework: Post proposal. Continue with planning.
CSC 405: Web Application And Engineering II7.1 Database Programming with SQL Aggregation and grouping with GROUP BY Aggregation and grouping with GROUP.
Creating Databases for Web Applications Reprise: Systems design (diagrams) Flash to php Homework: Prepare for quiz.
15/10/20151 PHP & MySQL 'Slide materials are based on W3Schools PHP tutorial, 'PHP website 'MySQL website.
Introduction to MySQL Lab no. 10 Advance Database Management System.
PHP MySQL Introduction. MySQL is the most popular open-source database system. What is MySQL? MySQL is a database. The data in MySQL is stored in database.
Creating Dynamic Web Pages Using PHP and MySQL CS 320.
Creating databases for web applications Database datatypes. Creating database Homework: Create tables in database. Add records to database.
Chapter 6 PHP Interacts with Mysql Database. Introduction In PHP, there is no consolidated interface. Instead, a set of library functions are provided.
SYST Web Technologies SYST Web Technologies Databases & MySQL.
Lecture 10 – MYSQL and PHP (Part 2)
Concepts of Database Management Seventh Edition
PHP+MySQL Integration. Connecting to databases One of the most common tasks when working with dynamic webpages is connecting to a database which holds.
Using Special Operators (LIKE and IN)
Concepts of Database Management Seventh Edition
HTML, PHP, and MySQL: Putting It All Together. Making a Form Input tags Types: “text” “radio” “checkboxes” “submit”
Creating databases for Web Applications php basics. ing. phpMyAdmin to set up MySQL. Homework: Use phpMyAdmin. Make posting with [unique] source on.
CISC 3140 (CIS 20.2) Design & Implementation of Software Application II Instructor : M. Meyer Address: Course Page:
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting PHP & MySQL.
Creating Databases Local storage. join & split Classwork: show 1 table application. Share designs for oscars application. Adaptive select. Homework: [Catch.
Creating Databases for web applications [Complete presentations] More SQL Class time: discuss final projects. Do posting if you have not done it.
Creating databases for web applications Library. New example: student database. Homework: Complete class example. Catch up on source postings. Do creation.
Create Databases for Web Applications Database normalization. Classwork/Homework: determine teams for basic projects explain and enhance assignment.
© Anselm Spoerri Web Design Information Visualization Course Prof. Anselm Spoerri
CpSc 462/662: Database Management Systems (DBMS) (TEXNH Approach) Relational Schema and SQL Queries James Wang.
Using Flash with php Very quick introduction to Flash Homework: work on projects.
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!
Chapter 8 Manipulating MySQL Databases with PHP PHP Programming with MySQL 2 nd Edition.
Creating Databases for Web Applications 3-Tier. Design vs Function vs Content. More SQL. More php. Homework: work on final projects.
Copyright © 2003 Pearson Education, Inc. Slide 8-1 The Web Wizard’s Guide to PHP by David Lash.
MICROSOFT ACCESS – CHAPTER 5 MICROSOFT ACCESS – CHAPTER 6 MICROSOFT ACCESS – CHAPTER 7 Sravanthi Lakkimsety Mar 14,2016.
Creating Databases for Web applications Making a table of table information. Reprise on database design. SQL. Classwork/Homework: Projects! Postings.
Confirm teams. Review of diagrams. SELECT problems.
Creating Databases Local storage. join & split
Creating databases for web applications
Creating databases for web applications
Creating Databases for Web Applications
Creating databases for web applications
Creating Databases More SQL. Design. Original Project Assignment
Creating Databases SELECT. UPDATE. Demonstrate projects. Do not track.
Web Programming– UFCFB Lecture
Presentation transcript:

Creating databases for web applications Report on using sources, getting examples working. Retrieve information from database. Recordsets. Arrays. Loops. Homework: Get examples working. Post unique source on entity relationship diagrams or data flow diagrams

Money example … and process First, quicktestexact: <? $test = $_GET["test"]; $pattern = "^(cat)|(dog)$"; if (eregi($pattern,$test)) { print("Entry $test passed the test"); } else { print("Entry $test failed the test"); } ?>

Method… Method in both senses of the word: Use Get so I can check using the query string: quicktestexact.php?test=cat …passes quicktestexact.php?test=mcat …fails

What does this do? <? $test = $_GET["test"]; $pattern = "^\\$[0-9]$"; if (eregi($pattern,$test)) { print("Entry $test passed the test"); } else { print("Entry $test failed the test"); } ?>

Work up … b/quicktestmcommas.php?test=$1,234http://newmedia.purchase.edu/~Jeanine/d b/quicktestmcommas.php?test=$1,234

Money with commas <? $test = $_GET["test"]; print ("string to be tested is $test"); $pattern = "^\\$[1-9][0-9]{0,2}(\,[0-9]{3})*(\.[0-9]{2})?$"; print (" "); print ("pattern is $pattern"); print (" "); if (ereg($pattern,$test)) { print("Entry $test passed the test"); } else { print("Entry $test failed the test"); } ?>

Report Did you create a table? Did you use sources?

Outline of work Understand php and MySQL examples –Get your own versions working Learn [about] system design and documentation –Find and study sources on ERD and DFD –Create diagrams for a library MIDTERM Design and build enhanced versions of sample projects Propose, design, present and build your own projects FINAL

Sample projects HTML & php –Quiz show –Orders –last time: Songs with features Flash ActionScript & php –Design plans –Video clip archive Demonstrate Reminder: code accessible from moodle My goal is 1 team for each!

Questions? Any problems creating tables in a database –If a table with that name exists, you need to DROP TABLE ….. before creating a new one INSERT INTO…. SELECT

Making connection A standard practice is to put the private information regarding the database in its own file, say it is called connectcode.php and then using require("connectcode.php"); In each program that requires connection to the database. My examples used files named opendb.php or something similar. Some of my examples use $DBname. That is, the code assumes that has been set with the database name.

Your database In the sent to you after the request for MySql access, there was –name, –database name –password In the following example, WKILLORAN is the name, WKILLORAN_DB is the database name and PASSWORD is the password. SUBSTITUTE FROM THE SENT TO YOU!

example of a fake connectcode.php file <?php $link = mysql_connect('localhost', 'WKILLORAN', 'PASSWORD'); if (!$link) { die('Not connected : '. mysql_error()); } if (!mysql_select_db('WKILLORAN_DB', $link)) { echo 'Could not select database'; exit; } $DBname = 'WKILLORAN_DB'; ?>

Simple example (assumes a connectcode.php file createtable.php enterstudent.html enterstudent.php showstudents.php showdepartments.php

createtable.php Creating student table <?php require("connectcode.php"); $tname = "students"; $fields = "sid INT NOT NULL AUTO_INCREMENT PRIMARY KEY, sname CHAR(30), sgpa FLOAT(5,4), sdept CHAR(30)"; $query = "DROP TABLE students"; mysql_query($query); $query = "CREATE TABLE $tname ($fields)"; if (mysql_query($query)) { print ("The table, $tname, was created successfully. \n"); } else { print ("The table, $tname, was not created. \n"); } mysql_close($link); ?>

enterstudent.html Input student Student Name Department GPA

enterstudent.php <?php require("connectcode.php"); $sn =$_GET['sn']; $sn = ADDSLASHES($sn); $sd=$_GET['sd']; $sd = ADDSLASHES($sd); $sgpa = $_GET['sgpa']; if (!is_numeric($sgpa)) { print ("Bad GPA data."); } else { $query="INSERT INTO students VALUES ("; $query.="'0','$sn',$sgpa,'$sd')"; print ("query is $query. "); if (mysql_query($query)) { print ("Student record added successfully"); } Else { print ("failure to add student record "); } } mysql_close($link); ?>

showstudents.php List contents of students table <?php require("connectcode.php"); $query="SELECT * FROM students"; $result=mysql_db_query($DBname, $query, $link); print(" "); print(" Student Department GPA "); while ($row=mysql_fetch_array($result)) { print(" "); print(" ".$row['sname']." "); print (" ".$row['sdept']." "); print (" ".$row['sgpa']." "); print (" "); } mysql_close($link); ?>

showdepartments.php List department average gpa and counts <?php require("connectcode.php"); $query="SELECT sdept, AVG(sgpa) as a, COUNT(*) as c FROM students GROUP BY sdept ORDER BY a DESC"; $result=mysql_db_query($DBname, $query, $link); print(" "); print(" Department Average GPA COUNT "); while ($row=mysql_fetch_array($result)) { print(" "); print(" ".$row['sdept']." "); print (" ".$row['a']." "); print (" ".$row['c']." "); print (" ");} mysql_close($link); ?>

MySQL queries ALL return something! This can be indication of success or a pointer to array (like) object holding data php has built-in commands for interactions with MySQL. NOTE: also has commands for generic DBMS –EXTRA CREDIT opportunity to report on php and other DBMS or report on comparisons.

Extra credit Report on Ruby on Rails Groovy ??

SELECT overview Extract some or all fields in table(s) –Also operations: COUNT, SUM, AVG Set conditions on which records by expression involving fields in one or more tables –WHERE, JOIN … ON Aggregate GROUP records Set conditions on the aggregated data HAVING Set LIMITS

Basic $query="SELECT * FROM movies"; Could have used $query ="SELECT mname, mdesc, myear FROM movies"; –Since I suggested not displaying the mid field Use $mysql_fetch_array to extract a row. This is an associative array that represents the constructed record of the selected data The results of $mysql_fetch_array can be used as a condition. When it fails, there were no more rows.

Performance how much time is taken by an SQL statement and/or php code This can be significant, that is, amount to something significant in large databases. DBMS have tools to determine this and you also can experiment.

Looping $query="SELECT * FROM movies"; $rs=mysql_query( $query); while ($row=mysql_fetch_array($rs)){ print($row['mname']. " (".$row['myear']. "): "); print($row['mdesc']); print(" "); }

What looping does Builds up a [long] string of html in this case (string encoded using my own design in the video clip archive case) Use the concatenate operator. Note [those pesky] single quotation marks –For the indexing into the associative array that is the row of data –For the attribute values in the html

Example from trivia quiz Each question has a designated category Objective: In HTML, build a pulldown menu as part of a form of the possible categories of questions Solution: use DISTINCT modified SELECT statement to get a recordset Use $mysql_fetch_array to extract a row. –This is an associative array that represents the constructed record of the selected data –The results of $mysql_fetch_array can be used as a condition. When it fails, there were no more rows. Use the data to build an element

From choosecategory.php Note: earlier code started the $query="SELECT DISTINCT category FROM questions"; $categories = mysql_db_query($query); while ($row=mysql_fetch_array($categories)) { $cat=$row['category']; print (" $cat \n"); }

Example from trivia quiz Decided on policy to NOT ask any question that a player had answered correctly OR a question posed that had been posed already that day. Solution: –build temporary table of questions answered correctly at any time or posed today. –Use so-called left join to choose questions that do NOT satisfy the constraint, that is, not in the temporary table

Caution / Encouragement SELECT statements can be equivalent to many lines of code So Give yourself time to understand and create it You do not have to do it the shortest way and/or only one statement. This may not even be the most efficient. Build up $query in stages (using.) and use print ("The query is $query"); at least with html/php. –Need to work harder with Flash! Set up a text area to display results.

$query="CREATE temporary TABLE past (item_id INT)"; $query=$query. " SELECT question_id FROM history where (player_id='".$player_id; $query=$query. "' AND (whenplayed='".$today."' OR correct))"; $result=mysql_db_query($query); $query="SELECT * FROM past"; $result = mysql_db_query($query); $Num_past = mysql_num_rows($result); if ($Num_past>0) { $sel = "SELECT questions.question_id, question, answerpattern, value from questions"; $sel =$sel. " LEFT JOIN past ON questions.question_id = past.question_id WHERE "; $sel = $sel. " category='". $pickedcategory. "' AND past.question_id IS NULL"; } else { $sel="SELECT question_id, question, answerpattern, value from questions "; $sel= $sel. " WHERE category= '". $pickedcategory. "'"; } $result=mysql_db_query( $sel);

Example from video clip archive Flash ActionScript implementation One table holds information on video clips Another table holds tags: one record for each tag and clip combinations. Since there can be any number of tags for a video clip, this cannot be a field in the main table.

Example, continued Objective: build tag area, with size dependent on number of clips with that tag. When player clicks on tag, build pulldown listing the clips. When player clicks on option, play the clip. Solution: use SELECT … JOIN … ON to select relevant records. Build string to be sent back to Flash program. Demonstrate: oject/tagdisplay.html oject/tagdisplay.html

$tag = $_GET['tag']; $query = "SELECT v.fileaddr, v.cliptitle FROM videoclips2 AS v JOIN taggedclips AS t ON v.fileaddr=t.fileaddr "; $query.= "WHERE t.tag='". $tag. "'"; $result = mysql_query($query); $sendback = ""; mysql_close(); $num = mysql_num_rows($result); $i = 0; while ($i<$num) { $fa = mysql_result($result,$i,"fileaddr"); $ct = mysql_result($result,$i,"cliptitle"); $sendback = $sendback. "$fa:$ct"; $i++; if ($i<$num) { $sendback = $sendback. ","; } } print "$sendback";

Comments The AS t and AS v allow you to use a shorter name in referencing the fields. Remember that equality condition in SQL is one equal sign. Remember to use single quotation marks around strings. –If $tag is a variable holding a string, the SQL statement needs the quotation marks! The 'sent back' data is itself encoded as a comma separated list of clip addresses and clip titles

GROUP HAVING SQL can aggregate (GROUP) records SQL can accept a condition applied to the GROUPs –The WHERE and the JOIN ON apply to the individual records GROUP generally is applied using aggregate functions, such as SUM, COUNT, AVG, MIN, MAX

Question Assume a table of student information, including major, gpa, credits What are the majors that have the highest averages among their students AND let's just consider juniors and seniors? –Define junior and senior as having more than 60 credits –Display the top 3 majors along with their average GPA

SELECT example SELECT department, AVG(gpa) FROM student_info WHERE credits >60 GROUP BY department HAVING AVG(gpa) > 3 ORDER BY AVG(gpa) DESC LIMIT 3 Select student records that have more than 60 credits. Group by common department. Take an average over the gpa fields. Just select those groups (that is, departments) where the average is over 3 (over B). Order from highest to lowest. Just take the first (top) 3.

Select example from songs with features (findothers2.php) $sid is the id of a selected song SELECT sname, COUNT(*) as c from featuresinsongs as f1, songs as s, featuresinsongs as f2 WHERE f1.sid='$sid' AND f1.fid=f2.fid AND f2.sid!='$sid' AND s.sid=f2.sid GROUP BY sname ORDER BY c DESC, sname The featuresinsongs table has song id field and feature id field. The name of a song is in the songs table. Select all the song and feature records that have features in common with features possessed by $sid. But don't select any song/feature row in which the song id IS $sid. Group by sname. Order from biggest to smallest.

3-tier model Database (MySQL data) holds the information. The middleware (php) is the application of the business decisions. The HTML and/or the FLASH program handles the interactions with people, including the presentation of results. Reflect on this in terms of examples.

Motivation for Diagrams Diagrams are tools for the design stage and for documentation. Databases that are more than one table are represented by Entity Relationship Diagrams. Applications (using databases or not) are represented by Data Flow diagrams. Database applications typically involve many small[er] files/programs/scripts. The exact structure of the diagrams less important than using some type of representation. Focus on this next class.

Homework Keep practicing with php and MySQL. Consider adding to the movies application. Find, review, and post reference and comments on unique source for Entity Relationship Diagrams and/or Data Flow Diagrams.