1 MySQL Using Databases with PHP or Perl Scripts:.

Slides:



Advertisements
Similar presentations
Copyright © 2003 Pearson Education, Inc. Slide 8-1 The Web Wizards Guide to PHP by David Lash.
Advertisements

CSE 1561 A Brief MySQL Primer Stephen Scott. CSE 1562 Introduction Once you’ve designed and implemented your database, you obviously want to add data.
A Guide to SQL, Seventh Edition. Objectives Understand the concepts and terminology associated with relational databases Create and run SQL commands in.
Chapter 7 Managing Data Sources. ASP.NET 2.0, Third Edition2.
Kirkwood Center for Continuing Education Introduction to PHP and MySQL By Fred McClurg, Copyright © 2010 All Rights Reserved. 1.
DAT702.  Standard Query Language  Ability to access and manipulate databases ◦ Retrieve data ◦ Insert, delete, update records ◦ Create and set permissions.
Introduction To Databases IDIA 618 Fall 2014 Bridget M. Blodgett.
Structured Query Language (SQL) A2 Teacher Up skilling LECTURE 2.
MySQL Dr. Hsiang-Fu Yu National Taipei University of Education
PHP1-1 PHP & SQL Xingquan (Hill) Zhu
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.
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.
Slide 8-1 CHAPTER 8 Using Databases with PHP Scripts: Using MySQL Database with PHP.
ASP.NET Programming with C# and SQL Server First Edition
Copyright © 2003 Pearson Education, Inc. Slide 8-1 The Web Wizard’s Guide to PHP by David Lash.
Relational DBs and SQL Designing Your Web Database (Ch. 8) → Creating and Working with a MySQL Database (Ch. 9, 10) 1.
PHP Programming with MySQL Slide 8-1 CHAPTER 8 Working with Databases and MySQL.
Mr. Justin “JET” Turner CSCI 3000 – Fall 2015 CRN Section A – TR 9:30-10:45 CRN – Section B – TR 5:30-6:45.
Web Server Administration Chapter 7 Installing and Testing a Programming Environment.
Chapter 7 Working with Databases and MySQL PHP Programming with MySQL 2 nd Edition.
Chapter 7 Working with Databases and MySQL PHP Programming with MySQL 2 nd Edition.
CHAPTER:14 Simple Queries in SQL Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्सजेंड़र ) PGT(CS),KV JHAGRAKHAND.
Ways to manage DB in MySQL cs346. Six ways to CREATE and INSERT INTO tables Modelocalremotelocalremotewindow WhereMysql console Putty; Mysql console Mysql.
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.
GUI To Create a DB Table CS346 Fall Methods to create a table At your local server and/or remote server – Use MySQL Console and create it interactively.
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.
Introduction to Internet Databases MySQL Database System Database Systems.
Web Scripting [PHP] CIS166AE Wednesdays 6:00pm – 9:50pm Rob Loy.
MySQL Databases & PHP Integration Using PHP to write data to, and retrieve data from, a MySQL database.
NMED 3850 A Advanced Online Design January 12, 2010 V. Mahadevan.
SYST Web Technologies SYST Web Technologies Databases & MySQL.
(Chapter 10 continued) Our examples feature MySQL as the database engine. It's open source and free. It's fully featured. And it's platform independent.
Concepts of Database Management Seventh Edition
Kirkwood Center for Continuing Education Introduction to PHP and MySQL By Fred McClurg, Copyright © 2015, Fred McClurg, All Rights.
Chapter 10: The Data Tier We discuss back-end data storage for Web applications, relational data, and using the MySQL database server for back-end storage.
Most information comes from Chapter 3, MySQL Tutorial: 1 MySQL: Part.
Visual C# 2012 How to Program © by Pearson Education, Inc. All Rights Reserved.
Web Server Administration Chapter 7 Installing and Testing a Programming Environment.
Database Fundamental & Design by A.Surasit Samaisut Copyrights : All Rights Reserved.
Visual Programing SQL Overview Section 1.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 (Part II) INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor.
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 22 - SQL, MySQL, DBI and ADO Outline 22.1 Introduction 22.2 Relational Database Model 22.3 Relational.
Chapter 8 Manipulating MySQL Databases with PHP PHP Programming with MySQL 2 nd Edition.
CP476 Internet Computing Perl CGI and MySql 1 Relational Databases –A database is a collection of data organized to allow relatively easy access for retrievals,
ECMM6018 Enterprise Networking For Electronic Commerce Tutorial 6 CGI/Perl and databases.
Database: SQL, MySQL, LINQ and Java DB © by Pearson Education, Inc. All Rights Reserved.
Distribution of Marks For Second Semester Internal Sessional Evaluation External Evaluation Assignment /Project QuizzesClass Attendance Mid-Term Test Total.
SQL pepper. Why SQL File I/O is a great deal of code Optimal file organization and indexing is critical and a great deal of code and theory implementation.
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.
CS320 Web and Internet Programming SQL and MySQL Chengyu Sun California State University, Los Angeles.
Programming for the Web MySQL Command Line Using PHP with MySQL Dónal Mulligan BSc MA
 MySQL is a database system used on the web  MySQL is a database system that runs on a server  MySQL is ideal for both small and large applications.
The Web Wizard’s Guide to PHP by David Lash
Web Systems & Technologies
Chapter 5 Introduction to SQL.
CS320 Web and Internet Programming SQL and MySQL
SQL and SQL*Plus Interaction
Introduction to MySQL.
JDBC.
ISC440: Web Programming 2 Server-side Scripting PHP 3
Chapter 7 Working with Databases and MySQL
Chapter 8 Working with Databases and MySQL
MySQL Dr. Hsiang-Fu Yu National Taipei University of Education
CS3220 Web and Internet Programming SQL and MySQL
MySQL Database System Installation Overview SQL summary
CS3220 Web and Internet Programming SQL and MySQL
MySQL Database System Installation Overview SQL summary
Presentation transcript:

1 MySQL Using Databases with PHP or Perl Scripts:

Objectives Advantages of using databases to store Web data How to prepare a MySQL database for use with Perl How to store, retrieve, and update data in a MySQL database

3 Data Driven Web Pages Approach 1 - Global variables –Disadvantage: Need to change program if data change Programs downstream need to change too Approach 2 - File Approach 3 - Database

4 To store data between executions of scripts: You may use files: –store customer data Login and password –store page hit counts –remember end-user preferences –store product inventory –Consumer survey Simple data structure

5 What is a database? A set of data organized into one or more computer files. Text file: A type of database –Using files for product inventory –A file, password.txt, to keep passwords Generally the term is reserved for more formal database systems like Access, Oracle or MySQL.

6 Advantages of Scripts Accessing Databases Over Scripts Using Files Faster access –DB performs the search (random access) vs. Sequential search - a line at a time in file Better concurrent access Easier changes to data and scripts –Need not know data file format Increased security –Perl scripts using files require access permissions set for all –DB uses separate ID and password to access WHH

7 Comparison: file vs Database FileDatabase AccesssequentialRandom Acc ContentsLong stringKeys, values MethodParseSQL Update fieldcumbersomesimple Suitable 1:Small filesLarge files Suitable 2:Simple dataComplex data Suitable 3:Few dataMany data

8 Relational Database? Relational databases store data in tables (usually more than one) with defined relationships between the tables.

9 Relational Database Model Database: collection of tables Table: collection of similar records Record: collection of values: Faculty table LastNameFirstNameBdgRoom BriscoeGarryHS218 FurcyDavidHS220 GeorgievGeorgeHS217 HuenWingHS221 NapsThomasHS216 YackelJonathanHS229

10 Relationship in Sample Database Courses NumInstructorTimeBdgRoom 221 Georgiev 9:10HS Yackel12:40HS Yackel1:50HS Perrie9:10HS Naps11:30C Huen8:00HS Huen10:20HS Naps11:30C44 431Perrie1:50HS367 LastnameFirstnameBdgRoom BriscoeGarryHS218 GeorgievGeorgeHS217 HuenWingHS215 NapsThomasHS216 PerrieAndrewHS221 YackelJonathanHS220 Faculty

11 Structured Query Language (SQL) Language for extracting/modifying data Every table has a name Every field/column has a name SHOW tables; SELECT * FROM Faculty;

12 SQL Select Statement Queries a database (read-only access) Returns a set of records What are first names of faculty? SELECT Firstname FROM Faculty; What classrooms are courses in? SELECT Num, Bdg, Room FROM Courses;

13 where clause: focus the query When does comp sci 310 meet? SELECT Time FROM Courses WHERE Num = 310; What is Huen's teaching schedule? SELECT Num, Time FROM Courses WHERE Instructor = ‘Huen‘;

14 Boolean Operators in WHERE clause What upper level courses is Huen teaching? SELECT Num FROM Courses WHERE Instructor = ‘Huen' AND Num >= 300; Note: Single quote for character strings. Hence Instructor = ‘O’’Hare’ What third-floor Halsey classrooms does the CS department teach in? SELECT Room FROM Courses WHERE Bdg='HS' AND Room >= 300 AND Room < 400;

15 Queries over Multiple Tables If two tables appear in FROM clause, DBMS generates cartesian product Use WHERE clause to " join " tables What are instructors’ first names for each course? SELECT Num, Firstname FROM Courses, Faculty WHERE Courses.Instructor = Faculty.Lastname

16 Duplicate Records Do not remove duplicates (default) SELECT ALL Instructor FROM Courses; SELECT Instructor FROM Courses; Explicitly remove duplicates SELECT DISTINCT Instructor FROM Courses;

17 Tuple Variables Who shares classrooms with Huen? Need to use the courses table twice. SELECT DISTINCT Instructor FROM Courses, Courses WHERE Bdg = Bdg AND Room = Room AND Instructor = ‘Huen’; Help, I'm confused! (…and so is the DBMS)

18 Tuple Variables We must differentiate between two uses of the same table SELECT DISTINCT x.instructor FROM Courses x, Courses y WHERE x.Bdg = y.Bdg AND x.Room = y.Room AND y.Instructor = ‘Huen’;

19 Counting Count the number of courses SELECT COUNT(*) FROM Courses Count the number of courses in Halsey SELECT COUNT(*) FROM Courses WHERE Bdg = ‘HS’; Count the number of rooms used SELECT COUNT(DISTINCT Room) FROM Courses;

20 GROUP BY Criteria for grouping records How many times is each room used? SELECT Room, COUNT(*) FROM Courses GROUP BY Room; How many courses is each room used for? SELECT Room, COUNT( DISTINCT Num) FROM Courses GROUP BY Room;

21 ORDER BY Criteria for ordering (sorting) records Get the faculty members in descending order of last name SELECT LastName, FirstName FROM Faculty ORDER BY LastName DESC; Multiple fields can be sorted too SELECT LastName, FirstName FROM Faculty ORDER BY LastName, FirstName;

22 Other Aggregate Functions MAX MIN SUM All used similar to COUNT What is the lowest numbered course? SELECT MIN(Num) FROM Courses;

23 Create a table CREATE TABLE Faculty( Lastname VARCHAR(10) NOT NULL PRIMARY KEY, Firstname VARCHAR(12), Bdg VARCHAR(10), room INT );

24 Insert a row INSERT INTO Faculty VALUES (‘Huen’, ‘Wing’, ‘HS’, 221); Better practice: More verbose and specific to avoid data mismatch INSERT INTO Faculty (FirstName, LastName, Bdg, Room) VALUES (‘Wing’, ‘Huen’, ‘HS’, 221);

25 UPDATING A RECORD UPDATE Tablename SET fieldName1 = value1, …, fieldNameN = valueN WHERE criteria; UPDATE Faculty SET Room = 221 WHERE LastName = ‘Huen’ AND FirstName = ‘Wing’;

26 DELETE FROM statement DELETE FROM TableName WHERE criteria DELETE FROM Faculty WHERE LastName = ‘Wing’ AND FirstName = ‘Huen’

PHP PHP DB functions 27

1. From MySQL Console 28 Enter password: Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 6 Server version: community-log MySQL Community Server (GPL) Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. mysql>

1. PHP to connect to MySQL MySQL must be running Need username and password –username = "cs346“ –password = "cs346_password“ SYNTAX: mysql_connect(“host", “username", “password") mysql_connect("localhost", "cs346", "cs346_password") 29

30 <?php $connection = mysql_connect("localhost", "cs346", "cs346_password") or die(mysql_error()); if ($connection) { $msg = "Connection to MySQL successful!"; } ?> MySQL Connection

Successful connection 31

Username or password does not match 32

2. List DB- From MySQL Console 33 mysql> show databases; | Database | | information_schema | | books | | cs346 | | mailinglist | | mysql | | products | rows in set (0.02 sec) mysql>

2. PHP listing databases 34

Some useful functions mysql_list_dbs() - used to list the databases on a MySQL server mysql_num_rows() - returns the number of rows in a result set mysql_tablename() - Though the name implies tablename only, it extracts names of tables, or databases from a result set 35

36 <?php $connection "cs346", "cs346_password") or die(mysql_error()); $dbs die(mysql_error()); $db_list =" "; $i =0; while ($i < mysql_num_rows($dbs)){ $db_names[$i] = mysql_tablename($dbs,$i); /* mysql_tablename(list_as_table, row_index) */ $db_list.= " $db_names[$i] "; // concatentation $i++; } $db_list.=" "; ?>

37 MySQL Databases Databases on localhost :

3. Show tables - from MySQL Console 38 mysql> use books; Database changed mysql> show tables; | Tables_in_books | | authorisbn | | authors | | titles | rows in set (0.13 sec)

39 mysql> use cs346; Database changed mysql> show tables; | Tables_in_cs346 | | movies | row in set (0.28 sec) mysql>

3. List tables - PHP MySQL Console: –use ; –Show tables; –One DB at a time PHP: –mysql_list_tables function –Use nested while loops –See 11-2db_listtables.php 40

41

42

43

4. Create database – from MySQL Console 44 mysql> create database testDB; Query OK, 1 row affected (0.19 sec) mysql> show databases; | Database | | information_schema | | books | | cs346 | | mailinglist | | mysql | | products | | testdb | rows in set (0.01 sec) mysql>

5. Drop database – from MySQL console 45 mysql> drop database testdb; Query OK, 0 rows affected (0.27 sec) mysql> show databases; | Database | | information_schema | | books | | cs346 | | mailinglist | | mysql | | products | rows in set (0.00 sec) mysql>

4. PHP to create DB $sql_string = “create database testDB2”; $connection “password") or die(mysql_error()); mysql_query($sql_string,$connection) or die(mysql_error()); 46

What happened? 47

Perhaps cs346 has no permission to create 48 mysql> select user, select_priv, insert_priv, create_priv from user; | user | select_priv | insert_priv | create_priv | | root | Y | Y | Y | | huen | Y | Y | Y | | cs346 | Y | Y | N | rows in set (0.00 sec)

Admin needs to grant permissions 49 mysql> GRANT CREATE on *.* TO Query OK, 0 rows affected (0.00 sec) mysql> select user, select_priv, insert_priv, create_priv from user; | user | select_priv | insert_priv | create_priv | | root | Y | Y | Y | | huen | Y | Y | Y | | cs346 | Y | Y | Y | rows in set (0.00 sec) mysql>

Now test again 50

Run 11-2db_listdb.php 51

5. PHP to drop DB $sql_string = “drop database testDB2”; $connection “password") or die(mysql_error()); mysql_query($sql_string,$connection) or die(mysql_error()); 52

Run 11-5db_dropdb.php 53

Admin to grant cs346 limited drop permissions 54 mysql> GRANT DROP ON testdb2.* TO Query OK, 0 rows affected (0.08 sec) mysql> select user, drop_priv from user; | user | drop_priv | | root | Y | | huen | Y | | cs346 | N | rows in set (0.00 sec) Note still drop_priv == N

Run 11-5db_dropdb.php again 55

Run 11-2db_listdb.php 56

Create tables And insert values 57

First create a DB with db_createdb.php 58

List DB 59

From Admin Create table my_music –Specify the fields and type Insert values into the table –Either interactively or –By batch – use source command 60

Use PHP 12-1show_createtable.html – form to enter –table name –number of attributes –Call PHP script to show field definitions 12-1do_showfielddef.php - form to enter –Field name –Field type –Field length 12-1do_createtable.php 61

12-1show_createtable.html 62

12-1do_showfielddef.php 63

On clicking the submit 64

Confirm table my_music in 2 ways From Admin –Show databases; –Use testdb1; –Show tables; –Describe my_music From PHP: –11-3db_listtables.php –Use mysql_query($sql,$connection) where $sql = ‘describe my_music’ 65

66 mysql> use testdb1; Database changed mysql> show tables; | Tables_in_testdb1 | | my_music | row in set (0.00 sec) mysql> describe my_music;

67 mysql> describe my_music; | Field | Type | Null | Key | Default | Extra | | id | int(5) | YES | | NULL | | | format | char(2) | YES | | NULL | | | title | varchar(150) | YES | | NULL | | | artist_fn | varchar(100) | YES | | NULL | | | artist_ln | varchar(100) | YES | | NULL | | | rec_label | varchar(50) | YES | | NULL | | | my_notes | text | YES | | NULL | | | date_acq | date | YES | | NULL | | rows in set (0.00 sec) mysql>

68

Insert values Locally (Admin) and remotely (PHP) 69

PHP to add record 13-1show_addrecord.html –Use a form to enter the field values –Submit the info to a PHP script 13-1do_addrecord.php 70

71

72

73

74

Check From MySQL Console mysql> select id, title, date_acq from my_music; | id | title | date_acq | | 1 | Pomp and Circumstance March No. 1 | | | 2 | The Four Seasons: Vivaldi | | rows in set (0.00 sec) mysql> PHP script: –mysql_query($sql,$connection)or die(mysql_error()); 75

Displaying Data in DB --- really it is via Select query 76

Display Info in DB Html for selecting by id, artist, date, etc. Different PHP scripts to send query 77

14-1my_menu.html 78

Ordered by ID 79

Ordered by Date Acquired 80

Ordered by Title 81

Ordered by Artist 82

Perl Perl DB functions 83

84 Some DB entry aid db_accessU.cgi, interactive GUI –One SQL statement at a time Create a script to enter multiple SQL statements in a batch = ( ‘DROP TABLE ingredient;’ ‘CREATE TABLE ingredient ( id VARCHAR(32) NOT NULL PRIMARY KEY, amt INTEGER UNSIGNED);’ “INSERT INTO ingredient VALUES(‘flour’,1);” )

85 Connect, query, disconnect Both db_accessU.cgi and a batch script need to –‘Connect’ to a database by logging in with username and password –‘prepare’ a query –‘execute’ the query –‘fetch a row’ from the specified table –‘disconnect’ from the database

86 Perl Database Interface DBI Use DBI –Object-oriented interface Driver Handle –Encapsulates the driver for the database Database handle –Encapsulates a specific connection to a database; can send SQL statements to a database Statement handle –Encapsulates specific SQL statements and the results returned from them

87 Connection to DB use DBI;# load DBI.pm use DBD::mysql;# Load the DB Driver If( $db_handle = DBI -> connect (“DBI:mysql:$dbName:$opt_host”, “username”, “password”) ) { # print success

88 prepare and execute query # prepare the query if( $stmt_handle = $db_handle -> prepare($sqlstmt) ) print ‘Success’; # execute the query if( $stmt_handle -> execute()) print “Success”;

89 Fetch a row from table While = $stmt_handle -> fetchrow_array()) {# process the row }

90 Disconnect from DB $db_handle -> disconnect();