* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Download My DB and PHP Access slides
Survey
Document related concepts
Relational algebra wikipedia , lookup
Microsoft Access wikipedia , lookup
Oracle Database wikipedia , lookup
Entity–attribute–value model wikipedia , lookup
Extensible Storage Engine wikipedia , lookup
Concurrency control wikipedia , lookup
Functional Database Model wikipedia , lookup
Microsoft SQL Server wikipedia , lookup
Ingres (database) wikipedia , lookup
Microsoft Jet Database Engine wikipedia , lookup
Versant Object Database wikipedia , lookup
ContactPoint wikipedia , lookup
Open Database Connectivity wikipedia , lookup
Clusterpoint wikipedia , lookup
Transcript
MySQL Using Databases with PHP or Perl Scripts 1 Objectives • Advantages of using databases to store Web data • How to prepare a MySQL database for use with PHP or Perl • How to store, retrieve, and update data in a MySQL database 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 3 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 4 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. 5 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 6 Comparison: file vs Database File Database Access sequential Random Acc Contents Long string Keys, values Method Parse SQL Update field cumbersome simple Suitable 1: Small files Large files Suitable 2: Simple data Complex data Suitable 3: Few data Many data 7 Relational Database? • Relational databases store data in tables (usually more than one) with defined relationships between the tables. Primary key Product Number Product Cost Weight Number Avail 0 Hammer $5.00 12 123 1 Screw Driver $3.00 2 144 2 Wrench $2.50 1.5 244 8 Relational Database Model • Database: collection of tables • Table: collection of similar records • Record: collection of values: Faculty table LastName FirstName Bdg Room Briscoe Garry HS 218 Furcy David HS 220 Georgiev George HS 217 Huen Wing HS 221 Naps Thomas HS 216 Yackel Jonathan HS 229 9 Relationship in Sample Database Faculty Courses Num Instructor Time Bdg Room 221 Georgiev 9:10 HS 237 221 Yackel 12:40 HS 212 221 Yackel 1:50 HS 212 243 Perrie 9:10 HS 208 300 Naps 11:30 C 243 321 Huen 8:00 HS 456 346 Huen 10:20 HS 367 262 Naps 11:30 C 44 431 Perrie 1:50 HS 367 Lastname Firstname Bdg Room Briscoe Garry HS 218 Georgiev George HS 217 Huen Wing HS 215 Naps Thomas HS 216 Perrie Andrew HS 221 Yackel Jonathan HS 220 Note: This is a bad DB design but sufficient at this stage for illustration. 10 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; 11 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; 12 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’; 13 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; 14 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 15 Duplicate Records • Do not remove duplicates (default) SELECT ALL Instructor FROM Courses; SELECT Instructor FROM Courses; • Explicitly remove duplicates SELECT DISTINCT Instructor FROM Courses; 16 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) 17 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’; 18 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; 19 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; 20 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; 21 Other Aggregate Functions • MAX • MIN • SUM All used similar to COUNT • What is the lowest numbered course? SELECT MIN(Num) FROM Courses; 22 Revisit Sample Database – PK and FK Faculty Courses Num Instructor Time Bdg Room 221 Georgiev 9:10 HS 237 221 Yackel 12:40 HS 212 221 Yackel 1:50 HS 212 243 Perrie 9:10 HS 208 300 Naps 11:30 C 243 321 Huen 8:00 HS 456 346 Huen 10:20 HS 367 262 Naps 11:30 C 44 431 Perrie 1:50 HS 367 Lastname Firstname Bdg Room Briscoe Garry HS 218 Georgiev George HS 217 Huen Wing HS 215 Naps Thomas HS 216 Perrie Andrew HS 221 Yackel Jonathan HS 220 What if multiple faculty members with same Lastname? How to use the tables for multiple semesters? 23 Improved DB Design • See DB_PK_FK.xls • See books DB in examples (view under C:\wamp\bin\mysql\mysql5.1.36\data) 24 Create a table CREATE TABLE Faculty( Fid INT UNSIGNED NOT NULL PRIMARY KEY, Lname VARCHAR(20) NOT NULL, Fname VARCHAR(20) NOT NULL, Bdg VARCHAR(10), room INT ); 25 Insert a row INSERT INTO Faculty VALUES (038, ‘Huen’, ‘Wing’, ‘HS’, 215); • Better practice: More verbose and specific to avoid data mismatch INSERT INTO Faculty (FID, FName, LName, Bdg, Room) VALUES (038,‘Wing’, ‘Huen’, ‘HS’, 221); 26 UPDATING A RECORD UPDATE Tablename SET fieldName1 = value1, …, fieldNameN = valueN WHERE criteria; UPDATE Faculty SET Room = 221 WHERE LName = ‘Huen’ AND FName = ‘Wing’; 27 DELETE FROM statement • DELETE FROM TableName WHERE criteria DELETE FROM Faculty WHERE LastName = ‘Wing’ AND FirstName = ‘Huen’ 28 PHP PHP DB functions 29 1. From MySQL Console Enter password: Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 6 Server version: 5.1.36-community-log MySQL Community Server (GPL) Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. mysql> 30 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") 31 <?php $connection = mysql_connect("localhost", "cs346", "cs346_password") or die(mysql_error()); if ($connection) { $msg = "Connection to MySQL successful!"; } ?> <html> <head> <title>MySQL Connection</title> </head> <body> <?php echo "$msg"; ?> </body> </html> 32 Successful connection 33 Username or password does not match 34 2. List DB- From MySQL Console mysql> show databases; +--------------------+ | Database | +--------------------+ | information_schema | | books | | cs346 | | mailinglist | | mysql | | products | +--------------------+ 6 rows in set (0.02 sec) mysql> 35 2. PHP listing databases 36 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 37 <?php $connection = @mysql_connect("localhost", "cs346", "cs346_password") or die(mysql_error()); $dbs = @mysql_list_dbs($connection)or die(mysql_error()); $db_list ="<ul>"; $i =0; while ($i < mysql_num_rows($dbs)){ $db_names[$i] = mysql_tablename($dbs,$i); /* mysql_tablename(list_as_table, row_index) */ $db_list .= "<li>$db_names[$i]</li>"; // concatentation $i++; } $db_list .="</ul>"; ?> 38 <html> <head> <title>MySQL Databases</title> </head> <body> <p><strong>Databases on localhost</strong>:</p> <?php echo "$db_list"; ?> </body> </html> 39 3. Show tables - from MySQL Console mysql> use books; Database changed mysql> show tables; +-----------------+ | Tables_in_books | +-----------------+ | authorisbn | | authors | | titles | +-----------------+ 3 rows in set (0.13 sec) 40 mysql> use cs346; Database changed mysql> show tables; +-----------------+ | Tables_in_cs346 | +-----------------+ | movies | +-----------------+ 1 row in set (0.28 sec) mysql> 41 3. List tables - PHP • MySQL Console: – use <database_name>; – Show tables; – One DB at a time • PHP: – mysql_list_tables function – Use nested while loops – See 11-2db_listtables.php 42 43 44 45 4. Create database – from MySQL Console mysql> create database testDB; Query OK, 1 row affected (0.19 sec) mysql> show databases; +--------------------+ | Database | +--------------------+ | information_schema | | books | | cs346 | | mailinglist | | mysql | | products | | testdb | +--------------------+ 7 rows in set (0.01 sec) mysql> 46 5. Drop database – from MySQL console mysql> drop database testdb; Query OK, 0 rows affected (0.27 sec) mysql> show databases; +--------------------+ | Database | +--------------------+ | information_schema | | books | | cs346 | | mailinglist | | mysql | | products | +--------------------+ 6 rows in set (0.00 sec) mysql> 47 4. PHP to create DB • $sql_string = “create database testDB2”; • $connection = @mysql_connect("localhost",“username", “password") or die(mysql_error()); • mysql_query($sql_string,$connection) or die(mysql_error()); 48 What happened? 49 Perhaps cs346 has no permission to create mysql> select user, select_priv, insert_priv, create_priv from user; +-------+-------------+-------------+-------------+ | user | select_priv | insert_priv | create_priv | +-------+-------------+-------------+-------------+ | root | Y | Y | Y | | root | Y | Y | Y | | huen | Y | Y | Y | | cs346 | Y | Y | N | +-------+-------------+-------------+-------------+ 4 rows in set (0.00 sec) 50 Admin needs to grant permissions mysql> GRANT CREATE on *.* TO 'cs346'@localhost; 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 | | root | Y | Y | Y | | huen | Y | Y | Y | | cs346 | Y | Y | Y | +-------+-------------+-------------+-------------+ 4 rows in set (0.00 sec) mysql> 51 Now test again 52 Run 11-2db_listdb.php 53 5. PHP to drop DB • $sql_string = “drop database testDB2”; • $connection = @mysql_connect("localhost",“username", “password") or die(mysql_error()); • mysql_query($sql_string,$connection) or die(mysql_error()); 54 Run 11-5db_dropdb.php 55 Admin to grant cs346 limited drop permissions mysql> GRANT DROP ON testdb2.* TO 'cs346'@localhost; Query OK, 0 rows affected (0.08 sec) mysql> select user, drop_priv from user; +-------+-----------+ | user | drop_priv | +-------+-----------+ | root | Y | | root | Y | | huen | Y | | cs346 | N | +-------+-----------+ 4 rows in set (0.00 sec) Note still drop_priv == N 56 Run 11-5db_dropdb.php again 57 Run 11-2db_listdb.php 58 Create tables And insert values 59 First create a DB with db_createdb.php 60 List DB 61 From Admin • Create table my_music – Specify the fields and type • Insert values into the table – Either interactively or – By batch – use source command 62 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 63 12-1show_createtable.html 64 12-1do_showfielddef.php 65 On clicking the submit 66 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’ 67 mysql> use testdb1; Database changed mysql> show tables; +-------------------+ | Tables_in_testdb1 | +-------------------+ | my_music | +-------------------+ 1 row in set (0.00 sec) mysql> describe my_music; 68 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 | | +-----------+--------------+------+-----+---------+-------+ 8 rows in set (0.00 sec) mysql> 69 70 Insert values Locally (Admin) and remotely (PHP) 71 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 72 73 74 75 76 Check • From MySQL Console mysql> select id, title, date_acq from my_music; +------+-----------------------------------+------------+ | id | title | date_acq | +------+-----------------------------------+------------+ | 1 | Pomp and Circumstance March No. 1 | 2005-06-19 | | 2 | The Four Seasons: Vivaldi | 2006-07-20 | +------+-----------------------------------+------------+ 2 rows in set (0.00 sec) mysql> • PHP script: – mysql_query($sql,$connection)or die(mysql_error()); 77 Displaying Data in DB --- really it is via Select query 78 Display Info in DB • Html for selecting by id, artist, date, etc. • Different PHP scripts to send query 79 14-1my_menu.html 80 Ordered by ID 81 Ordered by Date Acquired 82 Ordered by Title 83 Ordered by Artist 84 Perl Perl DB functions 85 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 My @sql = ( ‘DROP TABLE ingredient;’ ‘CREATE TABLE ingredient ( id VARCHAR(32) NOT NULL PRIMARY KEY, amt INTEGER UNSIGNED);’ “INSERT INTO ingredient VALUES(‘flour’,1);” ) 86 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 87 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 88 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 89 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”; 90 Fetch a row from table While ( @row = $stmt_handle -> fetchrow_array()) { # process the row } 91 Disconnect from DB $db_handle -> disconnect(); 92