MYSQL DATABASE ACCESS WITH PHP Fall 2009 CSCI 2910 Server Side Web Programming Typical web application interaction Database Server 3 tiered architecture Security in this interaction is critical Web Server User Web Browser Interface 1
MySQL Free, open source, high performance database engine. Most popular open source DB. http://www.mysql.com/ / MySQL Enterprise available as paid annual subscription with additional tools, support, etc. Part of common open source LAMP Web deployment architecture Linux, Apache, MySQL, yq, PHP. Architecture Components MySQL Server Available for all modern server OS. (Requires C++ and support for multi threading.) th Working with server 3 methods: MySQL Monitor executed from terminal window on server (command line tool, part of server install) MySQLMonitor Monitor executed from different server, connecting to target server. (Target server account must permit remote log in.) MySQL GUI Tools MySQL Administrator, MySQL Query Browser, and MySQL Migration Toolkit. 2
Working with server security issues Many organizations (and Web hosting companies) disable remote access for security reasons. They only acceptlocalhost logins. Many Web hosts do not allow MySQL Monitor or other GUI tool access. Packages like phpmyadmin allow MySQL database management via a web based GUI. 3
Using MySQL monitor To connect: 1. Use PuTTY to connect to Einstein terminal window (SSH connection) 2. At Einstein prompt enter mysql u abc123 p substituting your account name for abc123 u indicates the field that follows is your username p indicates that you will supply a password 3. Enter your password when prompted. (Initial password is 12345.) 4. An optional h parameter can be used to specify a remote host. 4
Working in MySQL monitor To change your MySQL password: set password = password("mynewpassword"); All statements end in a semicolon. If not supplied on enter, prompted to continue entering statement (or semicolon). Up arrow and down arrow permit scrolling through previous commands. If you've typed a portion of a command and wish to "abandon" it, type \c and press enter. More about the monitor You can enter individual queries/commands or create an SQL script in a text editor. (It must be plain text.) ) Save the file with an.sql extension. Use # at the beginning of the line for a comment. Upload the file to server via sftp. Place in same directory as where MySQL is launched, typically account root (not web site root). To execute the script, enter \. scriptname.sql (slash, period, space, scriptname). (Don't forget the space!) 5
Working in MySQL monitor See list of databases: show databases; Select a database to use: use databasename; Database for class is the same as your account name. See list of tables in database: show tables; Show columns in a table: show columns from tablename; or describe tablename; To exit the monitor: exit or \q Quick Database Review What is a database? Organized collection of related data. Requires data collection, maintenance, and ability to be used. Relational database: Divided into logical units called tables. Tables related to one another within the database. Allows data to be broken down into moremanageable manageable units, allowing easier maintenance and improved performance. Each table has a field (or set of fields) that provides a unique identifier in each record. 6
Terminology A single row in a table is called a record. A table column is called a field. Data is retrieved from a database by executing a query. Show the name of student_id 111111. By having common keys, data from multiple tables can be brought together into a result set. Show the names of all the students from Idaho. Example Relations 1:1 1:* *:1 7
Creating Tables Database design generally begins with tables. Every table is named and consists of entities called fields which h describe information i stored in a table. Fields can be optional or required. An optional value that is left empty is said to be null. Null is not blank or 0, it is null. Not an error, unless field is specifically designated as not null (meaning a value is required). Fields are of a designated type which defines permissible values and storage space allocation. Common MySQL Data Types Type CHAR[length] VARCHAR[length] TEXT MEDIUMTEXT LONGTEXT TINYINT SMALLINT MEDIUMINT INT BIGINT FLOAT DOUBLE DECIMAL[length, decimals] Description Fixed length character field, exactly size length. Max length 255 chars Variable length character field, up to size length. Max length 255 chars String, max length ~65k chars String, max length ~16 million chars String, max length ~4 billion chars 128 to 127 (0 to 255 if designated UNSIGNED) ~ 32k to ~32k (also available UNSIGNED) ~ 8 million to ~8 million (also available UNSIGNED) ~ 2 billion to 2 billion (also available UNSIGNED) ~ 9 quintillion to 9 quintillion (also available UNSIGNED) ~38 digit significant decimal number ~308 digit significant decimal number Double, stored to preserve precision with a fixed decimal point 8
Common MySQL Data Types, cont. Type DATE DATETIME TIMESTAMP TIME YEAR YYYY MM DD YYYY MM DD HH:MM:SS YYYYMMDDHHMMSS HH:MM:SS YYYY Description When defining fields, can specify UNSIGNED, ZEROFILL, and NOT NULL. cost DECIMAL(5,2) UNSIGNED NOT NULL Timestamp is special when insert or update occurs, this field automatically set. Design principle: Use the smallest appropriate data type. Full Example Table Definition Field Name user_id first_name last_name email password registration_date last_login users Type MEDIUMINT UNSIGNED NOT NULL VARCHAR(26) NOT NULL VARCHAR(30) NOT NULL VARCHAR(60) CHAR(16) NOT NULL DATETIME NOT NULL DATETIME Full overview of MySQL data types: http://dev.mysql.com/doc/refman/5.0/en/data types.html 9
Table Creation Process What data will be entered into the table? What will be the table's name? What field(s) will compose the primary key? What names shall be given to the fields? What data type will be assigned to each field? What will be the allocated length for each field? Is the field optional or required (not null)? Table Creation Syntax CREATE TABLE table_name ( field_name data_type [NOT NULL], PRIMARY KEY (field_name)); CREATE TABLE EMPLOYEE_TBL_DEMO ( EMP_ID CHAR(9)NOT NULL, EMP_NAME VARCHAR(40)NOT NULL, EMP_ST_ADDR VARCHAR(20), PRIMARY KEY (EMP_ID) ); DESCRIBE EMPLOYEE_TBL_DEMO; 10
Copying/Deleting an existing table CREATE TABLE NEW_TABLE AS SELECT * FROM OLD_TABLE; CREATE TABLE EMPLOYEE_TBL_DEMO AS SELECT * FROM EMPLOYEE_TBL; CREATE TABLE EMPLOYEE_TBL_DEMO_2 AS SELECT EMP_ID, LAST_NAME, FIRST_NAME FROM EMPLOYEE_TBL; DROP TABLE EMPLOYEE_TBL_DEMO_2; Inserting new data into a table INSERT INTO TABLE_NAME VALUE ( VAL1, ); INSERT INTO EMPLOYEE_TBL_DEMO VALUE ('123','Phil'Phil Smith','123 '123 Elm St.'); Works if inserting all fields in the order they appear in the table. INSERT INTO TABLE (FIELD1, ) VALUE ( VAL1, ); INSERT INTO EMPLOYEE_ TBL_ DEMO (EMP_ST_ADDR, EMP_NAME, EMP_ID) VALUE ('22 Poplar', 'Jo Johnson', '555'); For null values, list the word NULL (without quotes). 11
Updating existing table information UPDATE TABLENAME SET FIELD = VALUE WHERE FIELD = VALUE; May update 1 or more records in one operation. UPDATE ORDERS_TBL SET QTY = 1 WHERE ORD_NUM = '23E934'; UPDATE ORDERS_TBL SET QTY = 1; UPDATE ORDERS_TBL SET QTY = 10, CUST_ID = '221' WHERE ORD_NUM = '23E934'; DELETE Delete removes 1 or more records in their entirety from the table. DELETE FROM ORDERS_TBL WHERE ORD_NUM = '23A16'; DELETE FROM ORDERS_TBL WHERE QTY = 1; To delete all the records in a table: DELETE FROM ORDERS_TBL; 12
Querying the database Select is used to extract information based on specified criteria. SELECT * FROM PRODUCTS_TBL; TBL; Select statements consist of 4 distinct clauses: SELECT FROM WHERE ORDER BY Typically, SQL commands/keywords not casesensitivity. Data elements, fields, table names, etc. are. SELECT FROM SELECT [DISTINCT] [* or FIELD or FIELD, FIELD] SELECT position FROM EMPLOYEE_PAY_TBL; SELECT DISTINCT position FROM EMPLOYEE_PAY_TBL; SELECT position, pay_rate FROM EMPLOYEE_PAY_TBL; SELECT DISTINCT position, pay_rate FROM EMPLOYEE_PAY_TBL; _ SELECT * FROM ORDERS_TBL, PRODUCTS_TBL; 13
SELECT FROM WHERE Limits results returned based on condition(s). SELECT * FROM PRODUCTS_TBL WHERE COST > 10; SELECT * FROM PRODUCTS_TBL WHERE COST > 5 AND COST < 10; SELECT PROD_DESC, COST FROM PRODUCTS_TBL WHERE PROD_ID=119; SELECT EMP_ID FROM EMPLOYEE_TBL WHERE last_name= glass ; SELECT FROM WHERE ORDER BY Can list field to sort by. Ascending is default, DESC can be specified. SELECT PROD_DESC, DESC COST FROM PRODUCTS_TBL TBL WHERE COST<20 ORDER BY COST; SELECT PROD_DESC, COST FROM PRODUCTS_TBL WHERE COST<20 ORDER BY COST DESC; Shortcut can use integer to list column number to sort by in result set. SELECT PROD_DESC, COST FROM PRODUCTS_TBL WHERE COST<20 ORDER BY 1; 14
IS NULL The following is valid syntax, but likely incorrect: SELECT LAST_NAME FROM EMPLOYEE_TBL WHERE PAGER=NULL; The above looks for someone whose pager is the word NULL. SELECT LAST_NAME FROM EMPLOYEE_TBL WHERE PAGER IS NULL; BETWEEN Searches for a range of values within the range specified, including values on the boundary. SELECT * FROM PRODUCTS_TBL WHERE COST BETWEEN 5.95 AND 14.5; Could also state using >= and <= SELECT * FROM PRODUCTS_TBL WHERE COST >= 5.95 AND COST <= 14.5; 15
IN Allows listing of literal values to match. SELECT * FROM PRODUCTS_TBL WHERE PROD_ID IN ('13','9','87','119'); Like Allows value selection using wildcards: % represents 0 or more occurrences of any character _ (underscore) represents exactly 1 occurrence of any character SELECT * FROM EMPLOYEE_PAY_TBL WHERE EMP_ID LIKE '2%'; SELECT * FROM EMPLOYEE_PAY_TBL WHERE POSITION LIKE 'S%'; SELECT * FROM EMPLOYEE_PAY_TBL WHERE POSITION LIKE '_a%'; SELECT * FROM EMPLOYEE_PAY_TBL WHERE DATE_HIRE LIKE '%-06-%'; 16
AND, OR AND: Allows specifying multiple criteria all of which must be true for a match to occur. OR: Allows specifying multiple criteria any of which must be true for a match to occur. SELECT * FROM PRODUCTS_TBL WHERE PROD_ID = 9 OR PROD_ID=6; SELECT * FROM PRODUCTS_TBL WHERE PROD_ID = 9 OR 6; SELECT * FROM PRODUCTS_TBL WHERE PROD_ID = 9 AND PROD_ID=6; SELECT * FROM PRODUCTS_TBL WHERE PROD_ID = 9 OR COST < 8; NOT Reverses the meaning of the logical operator with which it is used. NOT EQUAL NOT BETWEEN NOT IN NOT LIKE IS NOT NULL 17
NOT Examples SELECT * FROM PRODUCTS_TBL WHERE COST NOT BETWEEN 5.95 AND 14.5; SELECT * FROM PRODUCTS_TBL WHERE PROD_ID NOT IN ('13','9','87','119'); SELECT PROD_DESC FROM PRODUCTS_TBL WHERE PROD_DESC NOT LIKE 'L%'; SELECT EMP_ID, LAST_NAME, FIRST_NAME, PAGER FROM EMPLOYEE_TBL WHERE PAGER IS NOT NULL; Functions Use COUNT function to count items in result set. Element in parenthesis is what will be counted. SELECT COUNT(*) FROM PRODUCTS_TBL; TBL Other functions: http://dev.mysql.com/doc/refman/5.0/en/func op summary ref.html 18
Joining Tables Joining tables brings together information from more than one table in a single query. Both tables are listed in the FROM clause. Join condition listed in the WHERE clause. Use tablename.field for clarity in overlapping field names. SELECT LAST_NAME, FIRST_NAME, PAY_RATE, SALARY FROM EMPLOYEE_TBL, EMPLOYEE_PAY_TBL WHERE EMPLOYEE_TBL.EMP_ID = EMPLOYEE_PAY_TBL.EMP_ID; The above is typically called an equijoin because the join is based on equality of the same field in different tables. Equijoin Structure SELECT TABLE1.COLUMN1, TABLE2.COLUMN2 FROM TABLE1, TABLE2 [, TABLE3 ] WHERE TABLE1.COLUMN_NAME= TABLE2.COLUMN_NAME [ AND TABLE1.COLUMN_NAME = TABLE3.COLUMN_NAME] 19
Examples SELECT EMPLOYEE_TBL.EMP_ID, EMPLOYEE_PAY_TBL.DATE_HIRE FROM EMPLOYEE_TBL,EMPLOYEE_PAY_TBL PAY WHERE EMPLOYEE_TBL.EMP_ID = EMPLOYEE_PAY_TBL.EMP_ID; SELECT EMPLOYEE_TBL.EMP_ID, EMPLOYEE_ TBL.LAST_ NAME, EMPLOYEE_PAY_TBL.POSITION FROM EMPLOYEE_TBL, EMPLOYEE_PAY_TBL WHERE EMPLOYEE_TBL.EMP_ID = EMPLOYEE_PAY_TBL.EMP_ID; Connecting to MySQL from PHP Typical steps in database transactions with PHP: 1.Connect to the RDBMS (Relational Database Management System). 2.Select a database to use. 3.Execute query. 4.Receive resultset from RDBMS. 5.Process the resultset. t 6.Close the RDBMS connection. Iterate as needed. 20
1. Connect to the RDBMS $conn = mysql_connect(host, username, password); If DB on same server as web server, can use "localhost" as the host name. $conn is set to a resource handle for accessing the connection or FALSE on failure. We can test $conn for connection success. @ will suppress errors from being written to the user display. If more than 1 connection needed to same host with same username/password, add TRUE as a 4 th parameter. Example <?php @$db = mysql_connect("localhost","demo", "demo"); if (!$db) echo "Cannot connect to MySQL"; else echo "Connection to MySQL successful";?> http://einstein.etsu.edu/~pittares/csci2910/examples/5 1.php 21
die() or exit() die($string) or exit($string) terminate script execution writing $string as error message. <?php @$db = mysql_connect("localhost","demo", "demo"); if (!$db) die("cannot connect to MySQL"); echo "Connection to MySQL successful";?> "or" based construction can be used based on PHP's short circuit evaluation of logical operators. http://einstein.etsu.edu/~pittares/csci2910/examples/5 2.php 2. Select a database to use If only one database to be opened: mysql_select_db('dbname'); If more than one database to be opened, list the connection to be used with a particular database. mysql_select_db('dbone', $db1); mysql_select_db('dbtwo', $db2); Most functions follow the pattern of having you specify the connection as the last parameter if more than 1 connection open. Returns FALSE if unable to select DB. http://einstein.etsu.edu/~pittares/csci2910/examples/5 3.php 22
3. Execute Queries $output = mysql_query($query); $output = mysql_query($query,$db1); The above allows the execution of any raw SQL (Select, Insert, Delete, Update, etc.) Query string ($query) cannot end in a semicolon. $output is a "complex" data type a resource handle to the resultset for Select, etc., boolean for Insert, Update, etc. 6. Close the database connection If only one (unnamed) connection open mysql_close(); If more than one connection open mysql_close($db1); PHP documentation claims close is unnecessary but some report it does affect performance. 23
Processing Select Resultset mysql_num_rows($resultset)returns number of lines returned by a select statement. http://einstein.etsu.edu/~pittares/csci2910/examples/5 4.php t i t /~ itt /CSCI2910/ /5 h Although this could be used to process resultset using a for loop, this is not typical. Recordset visualization Recordset returned as a complex data type. To display to user or otherwise incorporate into program logic, must parse out into elements. mysql_fetch_assoc(recordset) "pops" row off of recordset into an associative array and advanced internal pointer to next row. Returns false if there are no more rows to process key bday class name 24
Processing as an associative array $line = mysql_fetch_assoc($answer); The above retrieves the next line of the result set into an associative i array. http://einstein.etsu.edu/~pittares/csci2910/examples/5 5.php To handle individual fields: echo $line['fieldname']; http://einstein.etsu.edu/~pittares/csci2910/examples/5 6.php p// / p / / p / p p Loop through all lines in resultset using while loop. http://einstein.etsu.edu/~pittares/csci2910/examples/5 7.php http://einstein.etsu.edu/~pittares/csci2910/examples/5 8.php Fetch ing a line of the resultset mysql_fetch_assoc($resultset) returns next line of resultset as an associative array. while ($line = mysql_fetch_assoc($results)) lt echo $line['title']; mysql_fetch_row($resultset) returns next line of resultset as a numeric (0 based) array. while ($line = mysql_fetch_row($results)) echo $line[0]; //first field in results mysql_fetch_array($resultset) returns next line of resultset as both an associative and numeric array. 25
Taking apart a single row of a resultset A foreach loop can be used to process a single line of a resultset (just like a normal associative array). http://einstein.etsu.edu/~pittares/csci2910/examples/5 9.php t i t /~ itt /CSCI2910/ /5 9 h Technique can be used to build output in table format. http://einstein.etsu.edu/~pittares/csci2910/examples/5 10.php Table can be output with headers using mysql_data_seek($resultset, $row_to_seek); http://einstein.etsu.edu/~pittares/csci2910/examples/5 11.php Building a table from query results 1. Verify query returned results. 2. Output a table open tag. 3. Read first row of output into associative array. 4. Use a loop to output table header row containing field names. 5. Reset resultset pointer to row 0. 6. Use a loop to process all rows in resultset. t Use a nested foreach loop to process individual table cells. 7. Close the table 26
Freeing Resources Record sets returned from queries can be large. Use mysql_free_result($resultset) to conserve memory. (Automatically done at end of script.) Other Database Interaction Insert, Update, Delete, etc. feature similar code, but less involved processing of results. http://einstein.etsu.edu/~pittares/csci2910/examples/5 12.htm t i t /~ itt /CSCI2910/ /5 12 27
Other MySQL Operations Select, Show, Explain, and Describe return a record set or FALSE. Other operations (Insert, Update, etc.) return TRUE orfalse. mysql_list_dbs() returns, as a record set, the list of databases. mysql_list_tables($dbname) returns, as a recordset, the list of tables in a database. mysql_affected_rows() returns as an integer the number of rows affected by the last insert, update, etc. 28