Chapter 8 Manipulating MySQL Databases with PHP PHP Programming with MySQL 2 nd Edition.

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

Widhy Hayuhardhika NP, S.Kom. Overview of database structure Connecting to MySQL database Selecting the database to use Using the require_once statement.
Chapter 7 Working with Databases and MySQL
Manipulating MySQL Databases with PHP. PHP and mySQL2 Objectives Connect to MySQL from PHP Learn how to handle MySQL errors Execute SQL statements with.
Objectives Connect to MySQL from PHP
MySQL and PHP By Trevor Adams.
Intermediate PHP & MySQL
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.
ASP.NET Programming with C# and SQL Server First Edition Chapter 8 Manipulating SQL Server Databases with ASP.NET.
Introduction to Structured Query Language (SQL)
Website Development Working with MySQL. What you will achieve today! Connecting to mySql Creating tables in mySql Saving data on a server using mySql.
1 CS428 Web Engineering Lecture 23 MySQL Basics (PHP - VI)
What is MySQL? MySQL is a database. The data in MySQL is stored in database objects called tables. A table is a collections of related data entries and.
PHP1-1 PHP & SQL Xingquan (Hill) Zhu
© Yanbu University College YANBU UNIVERSITY COLLEGE Management Science Department © Yanbu University College Module 6:WEB SERVER AND SERVER SIDE SCRPTING,
A Guide to SQL, Eighth Edition Chapter Three Creating Tables.
Session 5: Working with MySQL iNET Academy Open Source Web Development.
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.
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:
Advanced Database Management System Lab no. 11. SQL Commands (for MySQL) –Update –Replace –Delete.
Chapter 7 PHP Interacts with Ms. Access (Open DataBase Connectivity (ODBC))
PHP Programming with MySQL Slide 8-1 CHAPTER 8 Working with Databases and MySQL.
PHP – MySQL Extensions. Table used in most examples CREATE TABLE product ( rowID INT NOT NULL AUTO_INCREMENT, productid VARCHAR(8) NOT NULL, name VARCHAR(25)
Objectives In this chapter, you will:
1 PHP and MySQL. 2 Topics  Querying Data with PHP  User-Driven Querying  Writing Data with PHP and MySQL PHP and MySQL.
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.
_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition1  Wiley and the.
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.
PHP MySQL. SQL: Tables CREATE TABLE tablename { fieldname type(length) extra info,... } Extra info: –NULL (allows nulls in this field) –Not NULL (null.
Creating Dynamic Web Pages Using PHP and MySQL CS 320.
Web Scripting [PHP] CIS166AE Wednesdays 6:00pm – 9:50pm Rob Loy.
Lec_6 Manipulating MySQL Databases with PHP PHP Programming with MySQL.
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.
1. Connecting database from PHP 2. Sending query 3. Fetching data 4. Persistent connections 5. Best practices.
Lecture 10 – MYSQL and PHP (Part 2)
PHP+MySQL Integration. Connecting to databases One of the most common tasks when working with dynamic webpages is connecting to a database which holds.
7 1 Chapter 7 Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
Web-Based Database Programming with PHP. Dept. of Computing Science, University of Aberdeen2 In this lecture you will learn PHP Basics PHP functions –To.
Pengantar Teknologi Internet W14: Server Scripting & Database.
Session 7: Getting PHP to Talk to MySQL. Objectives Connecting to the Database Building & Executing the SQL SELECT Query Fetching & Displaying the data.
CISC 3140 (CIS 20.2) Design & Implementation of Software Application II Instructor : M. Meyer Address: Course Page:
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting PHP & MySQL.
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting MySQL – Inserting Data.
PHP Database connectivity Connecting with RDBMS and editing, adding, and deleting databases therein are all done through PHP functions.
PHP Database Processing CIS 1715 Web Technologies.
Module Review Basic SQL commands: Create Database, Create Table, Insert and Select 2. Connect an SQL Database to PHP 3. Execute SQL Commands in.
NMD202 Web Scripting Week5. What we will cover today PHP & MySQL Displaying Dynamic Pages Exercises Modifying Data PHP Exercises Assignment 1.
Database Access Using JDBC BCIS 3680 Enterprise Programming.
Connecting, Queries, Best Practices Tran Anh Tuan Edit from Telerik Software Academy
CHAPTER 10 PHP MySQL Database
CSC 2720 Building Web Applications Accessing MySQL from PHP.
Copyright © 2003 Pearson Education, Inc. Slide 8-1 The Web Wizard’s Guide to PHP by David Lash.
MySQL Tutorial. Databases A database is a container that groups together a series of tables within a single structure Each database can contain 1 or more.
1 PHP and MySQL Web Development When you install PHP, you can select from a number of extensions. The MySQL support in PHP consists of a number of functions.
ASP.NET Programming with C# and SQL Server First Edition
Introduction to Web programming
Objectives Connect to MySQL from PHP Learn how to handle MySQL errors
ISC440: Web Programming 2 Server-side Scripting PHP 3
Chapter 7 Working with Databases and MySQL
Chapter 8 Working with Databases and MySQL
Tutorial 6 PHP & MySQL Li Xu
Web Programming– UFCFB Lecture
Introduction to Web programming
Presentation transcript:

Chapter 8 Manipulating MySQL Databases with PHP PHP Programming with MySQL 2 nd Edition

2PHP Programming with MySQL, 2nd Edition Objectives In this chapter, you will: Connect to MySQL from PHP Work with MySQL databases using PHP Create, modify, and delete MySQL tables with PHP Use PHP to manipulate MySQL records Use PHP to retrieve database records

3PHP Programming with MySQL, 2nd Edition Connecting to MySQL with PHP PHP has the ability to access and manipulate any database that is ODBC compliant PHP includes functionality that allows you to work directly with different types of databases, without going through ODBC PHP supports SQLite, database abstraction layer functions, and PEAR DB

4PHP Programming with MySQL, 2nd Edition Determining which MySQL Package to Use The mysqli (MySQL Improved) package became available with PHP 5 and is designed to work with MySQL version and later Earlier versions must use the mysql package The mysqli package is the object-oriented equivalent of the mysql package

5PHP Programming with MySQL, 2nd Edition Opening and Closing a MySQL Connection Open a connection to a MySQL database server with the mysql_connect() function The mysql_connect() function returns a positive integer if it connects to the database successfully or FALSE if it does not Assign the return value from the mysql_connect() function to a variable that you can use to access the database in your script

6PHP Programming with MySQL, 2nd Edition Opening and Closing a MySQL Connection (continued) The syntax for the mysql_connect() function is: $connection = mysql_connect("host" [, "user", "password"]); The host argument specifies the host name where your MySQL database server is installed The user and password arguments specify a MySQL account name and password

7PHP Programming with MySQL, 2nd Edition Opening and Closing a MySQL Connection (continued) The database connection is assigned to the $DBConnect variable $DBConnect = mysql_connect("localhost", "dongosselin ", "rosebud"); Close a database connection using the mysql_close() function mysql_close($DBConnect);

8PHP Programming with MySQL, 2nd Edition Opening and Closing a MySQL Connection (continued)

9PHP Programming with MySQL, 2nd Edition Opening and Closing a MySQL Connection (continued) Figure 8-1 MySQLInfo.php in a Web browser

10PHP Programming with MySQL, 2nd Edition Reporting MySQL Errors Reasons for not connecting to a database server include: –The database server is not running –Insufficient privileges to access the data source –Invalid username and/or password

Reporting MySQL Errors (continued) The mysql_errno() function returns the error code from the last attempted MySQL function call or 0 if no error occurred The mysql_errno() and mysql_error() functions return the results of the previous mysql*() function 11PHP Programming with MySQL, 2nd Edition

12PHP Programming with MySQL, 2nd Edition Suppressing Errors with the Error Control Operator By default, functions in the mysql package display errors and warnings as they occur Use the error control operator to suppress error messages The error control operator can be prepended to any expression although it is commonly used with expressions

Creating a Database Use the mysql_create_db() function to create a new database The basic syntax for the mysql_create_db() is: $result = mysql_create_db( "dbname" [, connection]); The mysql_create_db() returns a Boolean TRUE if successful or FALSE if there was an error 13PHP Programming with MySQL, 2nd Edition

Creating a Database (continued) Figure 8-2 Error message when the mysql_create_db() function is unavailable because of insufficient privileges 14PHP Programming with MySQL, 2nd Edition

15PHP Programming with MySQL, 2nd Edition Selecting a Database The syntax for the mysql_select_db() function is: mysql_select_db(database [, connection]); The function returns a value of TRUE if it successfully selects a database or FALSE if it does not For security purposes, you may choose to use an include file to connect to the MySQL server and select a database

Deleting a Database To delete a database, use the mysql_drop_db() function. The format for the mysql_drop_db() function is: $Result = mysql_drop_db("dbname" [, connection]); The function returns a value of TRUE if it successfully drops a database or FALSE if it does not 16PHP Programming with MySQL, 2nd Edition

17PHP Programming with MySQL, 2nd Edition Executing SQL Statements Use the mysql_query() function to send SQL statements to MySQL The syntax for the mysql_query() function is: mysql_query(query [, connection]); The mysql_query() function returns one of three values: –For SQL statements that do not return results ( CREATE DATABASE and CREATE TABLE statements) it returns a value of TRUE if the statement executes successfully

18PHP Programming with MySQL, 2nd Edition Executing SQL Statements (continued) –For SQL statements that return results ( SELECT and SHOW statements) the mysql_query() function returns a result pointer that represents the query results A result pointer is a special type of variable that refers to the currently selected row in a resultset –The mysql_query() function returns a value of FALSE for any SQL statements that fail, regardless of whether they return results

Creating and Deleting Tables Use the CREATE TABLE statement with the mysql_query() function to create a new table Use the mysql_select_db() function before executing the CREATE TABLE statement to verify that you are in the right database 19PHP Programming with MySQL, 2nd Edition

Creating and Deleting Tables (continued) $SQLstring = "CREATE TABLE drivers (name VARCHAR(100), ". "emp_no SMALLINT, hire_date DATE, ". "stop_date DATE)"; $QueryResult $DBConnect); if ($QueryResult===FALSE) echo " Unable to execute the query. ". " Error code ". mysql_errno($DBConnect). ": ". mysql_error($DBConnect). " "; else echo " Successfully created the table. "; 20PHP Programming with MySQL, 2nd Edition

Creating and Deleting Tables (continued) Figure 8-3 Error code and message that displays when you attempt to create a table that already exists 21PHP Programming with MySQL, 2nd Edition

22PHP Programming with MySQL, 2nd Edition Creating and Deleting Tables (continued) Use the SHOW TABLES LIKE command to prevent code from trying to create a table that already exists. If the table does not exist, the mysql_num_rows() function will return a value of 0 rows $TableName = "subscribers"; $SQLstring = "SHOW TABLES LIKE '$TableName'"; $QueryResult $DBConnect);

Creating and Deleting Tables (continued) To identify a field as a primary key in MySQL, include the PRIMARY KEY keywords when you define a field with the CREATE TABLE statement The AUTO_INCREMENT keyword is often used with a primary key to generate a unique ID for each new row in a table The NOT NULL keywords are often used with primary keys to require that a field include a value 23PHP Programming with MySQL, 2nd Edition

Creating and Deleting Tables (continued) To delete a table, use the DROP TABLE statement with the mysql_query() function 24PHP Programming with MySQL, 2nd Edition

Adding, Deleting, and Updating Records To add records to a table, use the INSERT and VALUES keywords with the mysql_query() function To add multiple records to a database, use the LOAD DATA statement with the name of the local text file containing the records you want to add To update records in a table, use the UPDATE statement 25PHP Programming with MySQL, 2nd Edition

Adding, Deleting, and Updating Records (continued) The UPDATE keyword specifies the name of the table to update The SET keyword specifies the value to assign to the fields in the records that match the condition in the WHERE clause To delete records in a table, use the DELETE statement with the mysql_query() function Omit the WHERE clause to delete all records in a table 26PHP Programming with MySQL, 2nd Edition

27PHP Programming with MySQL, 2nd Edition Retrieving Records into an Indexed Array The mysql_fetch_row() function returns the fields in the current row of a resultset into an indexed array and moves the result pointer to the next row echo " "; echo " Make Model Price Quantity "; $Row = mysql_fetch_row($QueryResult); do { echo " {$Row[0]} "; echo " {$Row[1]} "; echo " {$Row[2]} "; echo " {$Row[3]} "; $Row = mysql_fetch_row($QueryResult); } while ($Row);

28PHP Programming with MySQL, 2nd Edition Using the mysql_affected_rows() Function With queries that return results ( SELECT queries), use the mysql_num_rows() function to find the number of records returned from the query With queries that modify tables but do not return results ( INSERT, UPDATE, and DELETE queries), use the mysql_affected_rows() function to determine the number of affected rows

29PHP Programming with MySQL, 2nd Edition Using the mysql_affected_rows() Function (continued) $SQLstring = "UPDATE company_cars SET mileage= WHERE license='AK-1234'"; $QueryResult $DBConnect); if ($QueryResult === FALSE) echo " Unable to execute the query. ". " Error code ". mysql_errno($DBConnect). ": ". mysql_error($DBConnect). " "; else echo " Successfully updated ". mysql_affected_rows($DBConnect). " record(s). ";

30PHP Programming with MySQL, 2nd Edition Using the mysql_affected_rows() Function (continued) Figure 8-5 Output of mysql_affected_rows() function for an UPDATE query

31PHP Programming with MySQL, 2nd Edition Using the mysql_info() Function For queries that add or update records, or alter a table’s structure, use the mysql_info() function to return information about the query The mysql_info() function returns the number of operations for various types of actions, depending on the type of query The mysql_info() function returns information about the last query that was executed on the database connection

32PHP Programming with MySQL, 2nd Edition Using the mysql_info() Function (continued) The mysql_info() function returns information about queries that match one of the following formats: –INSERT INTO...SELECT... –INSERT INTO...VALUES (...),(...),(...) –LOAD DATA INFILE... –ALTER TABLE... –UPDATE For any queries that do not match one of these formats, the mysql_info() function returns an empty string

33PHP Programming with MySQL, 2nd Edition Using the mysql_info() Function (continued) $SQLstring = "INSERT INTO company_cars ". " (license, model_year, make, model, mileage) ". " VALUES ". " ('CPQ-894', 2011, 'Honda', 'Insight', 49.2), ". " ('CPQ-895', 2011, 'Honda', 'Insight', 17.9), ". " ('CPQ-896', 2011, 'Honda', 'Insight', 22.6)"; $QueryResult $DBConnect); if ($QueryResult === FALSE) echo " Unable to execute the query. ". " Error code ". mysql_errno($DBConnect). ": ". mysql_error($DBConnect). " "; else { echo " Successfully added the record. "; echo " ". mysql_info($DBConnect). " "; }

34PHP Programming with MySQL, 2nd Edition Using the mysql_info() Function (continued) Figure 8-6 Output of mysql_info() function for an INSERT query that adds multiple records

35PHP Programming with MySQL, 2nd Edition Using the mysql_info() Function (continued) The mysql_info() function also returns information for LOAD DATA queries $SQLstring = "LOAD DATA INFILE 'company_cars.txt' INTO TABLE company_cars;"; $QueryResult $DBConnect); if ($QueryResult === FALSE) echo " Unable to execute the query. ". " Error code ". mysql_errno($DBConnect). ": ". mysql_error($DBConnect). " "; else { echo " Successfully added the record. "; echo " ". mysql_info($DBConnect). " "; }

36PHP Programming with MySQL, 2nd Edition Using the mysql_info() Function (continued) Figure 8-7 Output of mysql_info() function for a LOAD DATA query

Working with Query Results 37PHP Programming with MySQL, 2nd Edition

Retrieving Records into an Indexed Array The mysql_fetch_row() function returns the fields in the current row of a result set into an indexed array and moves the result pointer to the next row 38PHP Programming with MySQL, 2nd Edition

Retrieving Records into an Indexed Array $SQLstring = "SELECT * FROM company_cars"; $QueryResult $DBConnect); echo " \n"; echo " License Make Model Mileage Year \n"; while (($Row = mysql_fetch_row($QueryResult)) !== FALSE) { echo " {$Row[0]} "; echo " {$Row[1]} "; echo " {$Row[2]} "; echo " {$Row[3]} "; echo " {$Row[4]} \n"; } echo " \n"; 39PHP Programming with MySQL, 2nd Edition

Retrieving Records into an Indexed Array 40PHP Programming with MySQL, 2nd Edition Figure 8-8 Output of the company_cars table in a Web Browser

41PHP Programming with MySQL, 2nd Edition Retrieving Records into an Associative Array The mysql_fetch_assoc() function returns the fields in the current row of a resultset into an associative array and moves the result pointer to the next row The difference between mysql_fetch_assoc() and mysql_fetch_row() is that instead of returning the fields into an indexed array, the mysql_fetch_assoc() function returns the fields into an associate array and uses each field name as the array key

42PHP Programming with MySQL, 2nd Edition Closing Query Results When you are finished working with query results retrieved with the mysql_query() function, use the mysql_free_result() function to close the resultset To close the resultset, pass to the mysql_free_result() function the variable containing the result pointer from the mysql_query() function

43PHP Programming with MySQL, 2nd Edition Accessing Query Result Information The mysql_num_rows() function returns the number of rows in a query result The mysql_num_fields() function returns the number of fields in a query result Both functions accept a database connection variable as an argument

44PHP Programming with MySQL, 2nd Edition Accessing Query Result Information (continued) $SQLstring = "SELECT * FROM company_cars"; $QueryResult $DBConnect); if ($QueryResult === FALSE) echo " Unable to execute the query. ". " Error code ". mysql_errno($DBConnect). ": ". mysql_error($DBConnect). " "; else echo " Successfully executed the query. "; $NumRows = mysql_num_rows($QueryResult); $NumFields = mysql_num_fields($QueryResult); if ($NumRows != 0 && $NumFields != 0) echo " Your query returned ". mysql_num_rows($QueryResult). " rows and ". mysql_num_fields($QueryResult). " fields. "; else echo " Your query returned no results. "; mysql_close($DBConnect);

45PHP Programming with MySQL, 2nd Edition Accessing Query Result Information (continued) Figure 8-10 Output of the number of rows and fields returned from a query

46PHP Programming with MySQL, 2nd Edition Summary The mysql_connect() function opens a connection to a MySQL database server The mysql_close() function closes a database connection The mysql_errno() function returns the error code from the last attempted MySQL function call or zero if no error occurred

47PHP Programming with MySQL, 2nd Edition Summary (continued) The mysql_error() function returns the error message from the last attempted MySQL function call or an empty string if no error occurred The error control operator suppresses error messages You use the mysql_create_db() function to create a new database The mysql_select_db() function selects a database

48PHP Programming with MySQL, 2nd Edition Summary (continued) You use the mysql_drop_db() function to delete a database The mysql_query() function sends SQL statements to MySQL A result pointer is a special type of variable that refers to the currently selected row in a resultset You use the CREATE TABLE statement with the mysql_query() function to create a table

49PHP Programming with MySQL, 2nd Edition Summary (continued) The PRIMARY KEY clause indicates a field or fields that will be used as a referential index for the table The AUTO_INCREMENT clause creates a field that is automatically updated with the next sequential value for that column The NOT NULL clause creates a field that must contain data You use the DROP TABLE statement with the mysql_query() function to delete a table

50PHP Programming with MySQL, 2nd Edition Summary (continued) You use the LOAD DATA statement and the mysql_query() function with a local text file to add multiple records to a database You use the UPDATE statement with the mysql_query() function to update records in a table You use the DELETE statement with the mysql_query() function to delete records from a table

51PHP Programming with MySQL, 2nd Edition Summary (continued) The mysql_info() function returns the number of operations for various types of actions, depending on the type of query. The mysql_fetch_row() function returns the fields in the current row of a resultset into an indexed array and moves the result pointer to the next row.

52PHP Programming with MySQL, 2nd Edition Summary (continued) The mysql_fetch_assoc() function returns the fields in the current row of a resultset into an associative array and moves the result pointer to the next row The mysql_free_result() function closes a resultset

53PHP Programming with MySQL, 2nd Edition Summary (continued) The mysql_num_rows() function returns the number of rows in a query result, and the mysql_num_fields() function returns the number of fields in a query result With queries that return results, such as SELECT queries, you can use the mysql_num_rows() function to find the number of records returned from the query