MySQL and PHP Integration Session 6 INFM 718N Web-Enabled Databases.

Slides:



Advertisements
Similar presentations
PHP II Interacting with Database Data. The whole idea of a database-driven website is to enable the content of the site to reside in a database, and to.
Advertisements

PHP and MySQL Database. Connecting to MySQL Note: you need to make sure that you have MySQL software properly installed on your computer before you attempt.
Web Database Programming Connecting Database to Web.
PHP Week 11 INFM 603. Thinking About PHP Local vs. Web-server-based display HTML as an indirect display mechanism “View Source” for debugging –But not.
Everyday Italian Giada De Laurentiis Harry Potter J K. Rowling Learning XML Erik T. Ray CSCI 305 Introduction to Database.
PHP (2) – Functions, Arrays, Databases, and sessions.
Debugging and Ajax Session 7 INFM 718N Web-Enabled Databases.
Database Design and MySQL
Objectives Connect to MySQL from PHP
XP 1 Working with JavaScript Creating a Programmable Web Page for North Pole Novelties Tutorial 10.
JavaScript and PHP Week 10 LBSC 690 Information Technology.
PHP Programming Session 2 INFM 718N Web-Enabled Databases.
MySQL and PHP By Trevor Adams.
MySQL and Requirements Session 4 INFM 718N Web-Enabled Databases.
Modular Programming and Use Case Models Session 3 LBSC 790 / INFM 718B Building the Human-Computer Interface.
Week 1 INFM 718N Web-Enabled Databases The Big Picture.
Web-Database Integration
PHP and MySQL Web Development tMyn1 PHP and MySQL Web Development When you install PHP, you can select from a number of extensions. The MySQL support in.
PHP Programming Part II and Database Design Session 3 INFM 718N Web-Enabled Databases.
Lecture 3 – Data Storage with XML+AJAX and MySQL+socket.io
Application Development Description and exemplification of server-side scripting language for server connection, database selection, execution of SQL queries.
© Yanbu University College YANBU UNIVERSITY COLLEGE Management Science Department © Yanbu University College Module 6:WEB SERVER AND SERVER SIDE SCRPTING,
Databases with PHP A quick introduction. Y’all know SQL and Databases  You put data in  You get data out  You can do processing on it very easily 
Session 5: Working with MySQL iNET Academy Open Source Web Development.
Chapter 5 Introduction to SQL. Structured Query Language = the “programming language” for relational databases SQL is a nonprocedural language = the user.
LIS651 lecture 7 PHP mySQL Thomas Krichel
MySQL in PHP – Page 1 of 17CSCI 2910 – Client/Server-Side Programming CSCI 2910 Client/Server-Side Programming Topic: MySQL in PHP Reading: Williams &
INTERNET APPLICATION DEVELOPMENT For More visit:
CHAPTER 12 COOKIES AND SESSIONS. INTRO HTTP is a stateless technology Each page rendered by a browser is unrelated to other pages – even if they are from.
Create an online booking system (login/registration)
1 PHP and MySQL. 2 Topics  Querying Data with PHP  User-Driven Querying  Writing Data with PHP and MySQL PHP and MySQL.
PHP meets MySQL.
INTRODUCTION TO JAVASCRIPT AND DOM Internet Engineering Spring 2012.
Accessing MySQL with PHP IDIA 618 Fall 2014 Bridget M. Blodgett.
XP Tutorial 10New Perspectives on Creating Web Pages with HTML, XHTML, and XML 1 Working with JavaScript Creating a Programmable Web Page for North Pole.
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.
Web Scripting [PHP] CIS166AE Wednesdays 6:00pm – 9:50pm Rob Loy.
Chapter 6 PHP Interacts with Mysql Database. Introduction In PHP, there is no consolidated interface. Instead, a set of library functions are provided.
1. Connecting database from PHP 2. Sending query 3. Fetching data 4. Persistent connections 5. Best practices.
Programming Week 11 LBSC 690 Information Technology.
Testing and Debugging Session 9 LBSC 790 / INFM 718B Building the Human-Computer Interface.
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
Variables and ConstantstMyn1 Variables and Constants PHP stands for: ”PHP: Hypertext Preprocessor”, and it is a server-side programming language. Special.
CHAPTER 9 PHP AND MYSQL. A POSSIBLE SITE CONFIGURATION Application Folder index.php includes (folder)header.phpfooter.phpstyle.cssmodel (folder)mysqli_connect.php.
HTML, PHP, and MySQL: Putting It All Together. Making a Form Input tags Types: “text” “radio” “checkboxes” “submit”
Intro to DatabasesClass 4 SQL REVIEW To talk to the database, you have to use SQL SQL is used by many databases, not just MySQL. SQL stands for Structured.
Creating PHPs to Insert, Update, and Delete Data CS 320.
PHP Week 8 INFM 603. Agenda Questions PHP Drupal Project Plan.
Just a Little PHP Programming PHP on the Server. Common Programming Language Features Comments Data Types Variable Declarations Expressions Flow of Control.
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting PHP & MySQL.
>> 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.
Copyright © 2003 ProsoftTraining. All rights reserved. Perl Fundamentals.
Creating a simple database This shows you how to set up a database using PHPMyAdmin (installed with WAMP)
Database Access Control IST2101. Why Implementing User Authentication? Remove a lot of redundancies in duplicate inputs of database information – Your.
Chapter 8 Manipulating MySQL Databases with PHP PHP Programming with MySQL 2 nd Edition.
CHAPTER 10 PHP MySQL Database
CSC 2720 Building Web Applications Accessing MySQL from PHP.
CSC 405: Web Application Engineering II8.1 Web programming using PHP What have we learnt? What have we learnt? Underlying technologies of database supported.
1 A Very Brief Introduction to Relational Databases.
Relational Databases (Part 2) Session 14 INST 301 Introduction to Information Science.
Chapter 5 Introduction to SQL.
Web Design and Development
Introduction to Web programming
ISC440: Web Programming 2 Server-side Scripting PHP 3
Tutorial 6 PHP & MySQL Li Xu
Introduction to Web programming
Presentation transcript:

MySQL and PHP Integration Session 6 INFM 718N Web-Enabled Databases

Agenda MySQL PHP-MySQL integration

Database Server-side Programming Interchange Language Client-side Programming Web Browser Client Hardware Server Hardware (PC, Unix) (MySQL) (PHP) (HTML, XML) (JavaScript) (IE, Firefox) (PC) Business rules Interaction Design Interface Design Relational normalization Structured programming Software patterns Object-oriented design Functional decomposition

Getting started with MySQL “root” creates database, grants permissions –By you on WAMP (mysql –u root –p) –By Charles Goldman on OTAL –CREATE DATABASE team1; –GRANT SELECT, INSERT, UPDATE, DELETE, INDEX, ALTER, CREATE, DROP ON team1.* TO IDENTIFIED BY ‘bar’; –FLUSH PRIVILEGES; Start mysql –Start->Run->cmd for WAMP, ssh for OTAL –mysql –u foo –p bar [you can cd to your playspace first, but you don’t need to] Connect to your database –USE team1;

Some Useful MySQL Commands Looking around –SHOW DATABASES; –SHOW TABLES; –DESCRIBE tablename; –SELECT * FROM tablename; Optimization –SHOW TABLE STATUS \G; OPTIMIZE TABLE tablename; –EXPLAIN ; ALTER TABLE tablename ADD INDEX fieldname;

Creating Tables CREATE TABLE contacts ( ckeyMEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT, idMEDIUMINT UNSIGNED NOT NULL, ctypeSMALLINT UNSIGNED NOT NULL, cstringVARCHAR(40) NOT NULL, FOREIGN KEY (id) REFERENCES persons(id) ON DELETE CASCADE, FOREIGN KEY (ctype) REFERENCES ctlabels(ctype) ON DELETE RESTRICT, PRIMARY KEY (ckey) ) ENGINE=INNODB;  To delete: DROP TABLE contacts;

Referential Integrity “Foreign key” values must exist in another table –If not, those records cannot be joined Checked when data added to this table –MySQL “Error 150” Triggers when data deleted/changed in other table –Specify SET NULL, RESTRICT or CASCADE

Populating Tables INSERT INTO ctlabels (string) VALUES ('primary '), ('alternate '), ('home phone'), ('cell phone'), ('work phone'), ('AOL IM'), ('Yahoo Chat'), ('MSN Messenger'), (‘other’);  To empty a table: DELETE FROM ctlabels;

The SQL SELECT Command SELECT (“projection”) chooses columns –Based on their label WHERE (“restriction”) chooses rows –Based on their contents e.g. department ID = “HIST” These can be specified together –SELECT Student ID, Dept WHERE Dept = “History”

WHERE Clause Each SELECT contains a single WHERE Numeric comparison, =, <>, … e.g., grade<80 Boolean operations –e.g., Name = “John” AND Dept <> “HIST”

Connecting PHP to MySQL On WAMP: $dbc=mysql_connect (‘localhost’, ‘userid’, ‘password’); On OTAL: $dbc=mysql_connect(‘:/export/software/otal/mysql/run/mysqld.sock’, ‘userid’, ‘password’);

<?php # Script mysql_connect.php // Set the database access information as constants. DEFINE ('DB_USER', 'tester'); DEFINE ('DB_PASSWORD', 'tester'); DEFINE ('DB_HOST', 'localhost'); DEFINE ('DB_NAME', 'sitename'); // Make the connection. $dbc (DB_HOST, DB_USER, DB_PASSWORD) OR die ('Could not connect to MySQL: '. mysql_error() ); // Select the (DB_NAME) OR die ('Could not select the database: '. mysql_error() ); // Create a function for escaping the data. function escape_data ($data) { // Address Magic Quotes. if (ini_get('magic_quotes_gpc')) { $data = stripslashes($data); } // Check for mysql_real_escape_string() support. if (function_exists('mysql_real_escape_string')) { global $dbc; // Need the connection. $data = mysql_real_escape_string (trim($data), $dbc); } else { $data = mysql_escape_string (trim($data)); } // Return the escaped value. return $data; } // End of function. ?>

<?php # Script login.php (7th version after Scripts 9.1, 9.3, 9.6, & 9.14) // Send NOTHING to the Web browser prior to the session_start() line! // Check if the form has been submitted. if (isset($_POST['submitted'])) { require_once ('../mysql_connect.php'); // Connect to the db. $errors = array(); // Initialize error array. // Check for an address. if (empty($_POST[' '])) { $errors[] = 'You forgot to enter your address.'; } else { $e = escape_data($_POST[' ']); } // Check for a password. if (empty($_POST['password'])) { $errors[] = 'You forgot to enter your password.'; } else { $p = escape_data($_POST['password']); }

if (empty($errors)) { // If everything's OK. /* Retrieve the user_id and first_name for that /password combination. */ $query = "SELECT user_id, first_name FROM users WHERE ='$e' AND password=SHA('$p')"; $result ($query); // Run the query. $row = mysql_fetch_array ($result, MYSQL_NUM); // Return a record, if applicable. if ($row) { // A record was pulled from the database. // Set the session data & redirect. session_name ('YourVisitID'); session_start(); $_SESSION['user_id'] = $row[0]; $_SESSION['first_name'] = $row[1]; $_SESSION['agent'] = md5($_SERVER['HTTP_USER_AGENT']); // Redirect the user to the loggedin.php page. // Start defining the URL. $url = ' $_SERVER['HTTP_HOST']. dirname($_SERVER['PHP_SELF']); // Check for a trailing slash. if ((substr($url, -1) == '/') OR (substr($url, -1) == '\\') ) { $url = substr ($url, 0, -1); // Chop off the slash. } // Add the page. $url.= '/loggedin.php'; header("Location: $url"); exit(); // Quit the script. } else { // No record matched the query. $errors[] = 'The address and password entered do not match those on file.'; // Public message. $errors[] = mysql_error(). ' Query: '. $query; // Debugging message. } } // End of if (empty($errors)) IF. mysql_close(); // Close the database connection. } else { // Form has not been submitted. $errors = NULL; } // End of the main Submit conditional.

// Begin the page now. $page_title = 'Login'; include ('./includes/header.html'); if (!empty($errors)) { // Print any error messages. echo ' Error! The following error(s) occurred: '; foreach ($errors as $msg) { // Print each error. echo " - $msg \n"; } echo ' Please try again. '; } // Create the form. ?> Login Address: Password: <?php include ('./includes/footer.html'); ?>

Arrays in PHP A set of key-element pairs $days = array(“Jan”->31, “Feb”=>28, …); $months = explode(“/”, “Jan/Feb/Mar/…/Dec”); $_POST Each element is accessed by the key –{$days[“Jan”]} –$months[0]; Arrays and loops work naturally together

Thinking about Arrays Naturally encodes an order among elements –$days = rksort($days); Natural data structure to use with a loop –Do the same thing to different data PHP unifies arrays and hashtables –Elements may be different types

Functions in PHP Declaration function multiply($a, $b=3){return $a*$b;} Invoking a method $b = multiply($b, 7); All variables in a function have only local scope Unless declared as global in the function

Why Modularity? Limit complexity –Extent –Interaction –Abstraction Minimize duplication

Sources of Complexity Syntax –Learn to read past the syntax to see the ideas –Copy working examples to get the same effect Interaction of data and control structures –Structured programming Modularity

Code Walkthrough Syntax How layout helps reading How variables are named How strings are used How forms are used How output is created MySQL Integration Opening a database Handling slashes Posing queries Using result sets Structured Programming How things are nested How arrays are used Modular Programming Functional decomposition How functions are invoked How arguments work How scope is managed How errors are handled How results are passed

Programming Skills Hierarchy Reusing code [run the book’s programs] Understanding patterns [read the book] Applying patterns [modify programs] Coding without patterns [programming] Recognizing new patterns

Best Practices Design before you build Focus your learning Program defensively Limit complexity Debug syntax from the top down

Rapid Prototyping + Waterfall Update Requirements Choose Functionality Build Prototype Initial Requirements Write Specification Create Software Write Test Plan

Focus Your Learning Find examples that work –Tutorials, articles, examples Cut them down to focus on what you need –Easiest to learn with throwaway programs Once it works, include it in your program –If it fails, you have a working example to look at

Defensive Programming Goal of software is to create desired output Programs transform input into output –Some inputs may yield undesired output Methods should enforce input assumptions –Guards against the user and the programmer! Everything should be done inside methods

Limiting Complexity Single errors are usually easy to fix –So avoid introducing multiple errors Start with something that works –Start with an existing program if possible –If starting from scratch, start small Add one new feature –Preferably isolated in its own method

Types of Errors Syntax errors –Detected at compile time Run time exceptions –Cause system-detected failures at run time Logic errors –Cause unanticipated behavior (detected by you!) Design errors –Fail to meet the need (detected by stakeholders)

Debugging Syntax Errors Focus on the first error message –Fix one thing at a time The line number is where it was detected –It may have been caused much earlier Understand the cause of “warnings” –They may give a clue about later errors If all else fails, comment out large code regions –If it compiles, the error is in the commented part

Run Time Exceptions Occur when you try to do the impossible –Use a null variable, divide by zero, … The cause is almost never where the error is –Why is the variable null? Exceptions often indicate a logic error –Find why it happened, not just a quick fix!

Debugging Run-Time Exceptions Run the program to get a stack trace –Where was this function called from? Print variable values before the failure Reason backwards to find the cause –Why do they have these values? If necessary, print some values further back

Logic Errors Evidenced by inappropriate behavior Can’t be automatically detected –“Inappropriate” is subjective Sometimes very hard to detect –Sometimes dependent on user behavior –Sometimes (apparently) random Cause can be hard to pin down

Debugging Logic Errors First, look where the bad data was created If that fails, print variables at key locations –if (DEBUG) echo “\$foobar = $foobar”; Examine output for unexpected patterns Once found, proceed as for run time errors –define (“DEBUG”, FALSE); to clean the output

Three Big Ideas Functional decomposition –Outside-in design High-level languages –Structured programming, object-oriented design Patterns –Design patterns, standard algorithms, code reuse

One-Minute Paper What was the muddiest point in today’s class? Be brief! No names!