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)

Slides:



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

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.
PHP and MySQL PHP for the Web, page PHP and MySQL MySQL Resource PHP – MySQL Resource
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.
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)
Lecture 3 – Data Storage with XML+AJAX and MySQL+socket.io
PHP : Working with Resultsets. Last class  Open a connection to the MySQL server.  Specify the database  Issue queries (no updates at this stage) 
Programming with php By: Seth Larson. A little bit about PHP  PHP stands for PHP:  Hypertext Preprocessor  PHP is a widely-used general-purpose server-side.
Application Development Description and exemplification of server-side scripting language for server connection, database selection, execution of SQL queries.
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,
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.
Copyright © 2003 Pearson Education, Inc. Slide 8-1 The Web Wizard’s Guide to PHP by David Lash.
1 PHP and MySQL. 2 Topics  Querying Data with PHP  User-Driven Querying  Writing Data with PHP and MySQL PHP and MySQL.
_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition1  Wiley and the.
Comp 519: Web Programming Autumn 2014 Advanced SQL and PHP Advanced queries Querying more than one table Searching tables to find information Aliasing.
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.
School of Computing and Information Systems CS 371 Web Application Programming PHP – Forms, Cookies, Sessions and Database.
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.
INTERNET APPLICATION DEVELOPMENT Practical on Sessions.
1. Connecting database from PHP 2. Sending query 3. Fetching data 4. Persistent connections 5. Best practices.
Lecture 10 – MYSQL and PHP (Part 2)
Accessing Your MySQL Database from the Web with PHP (Ch 11) 1.
Database Access with PHP and MySQL CS356 Examples from Web Database Applications, by Hugh E. Williams & David Lane, O'Reilly, 2002.
PHP+MySQL Integration. Connecting to databases One of the most common tasks when working with dynamic webpages is connecting to a database which holds.
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.
HTML, PHP, and MySQL: Putting It All Together. Making a Form Input tags Types: “text” “radio” “checkboxes” “submit”
CSC 2720 Building Web Applications Server-side Scripting with PHP.
CISC 3140 (CIS 20.2) Design & Implementation of Software Application II Instructor : M. Meyer Address: Course Page:
Creating PHPs to Insert, Update, and Delete Data CS 320.
PHP PHP: Hypertext Preprocesor Personal Home Page Tools.
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting PHP & MySQL.
Controlling Web Site Access Using Logins CS 320. Basic Approach HTML form a php page that collects the username and password  Sends them to second PHP.
Module Review Basic SQL commands: Create Database, Create Table, Insert and Select 2. Connect an SQL Database to PHP 3. Execute SQL Commands in.
>> 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.
NMD202 Web Scripting Week5. What we will cover today PHP & MySQL Displaying Dynamic Pages Exercises Modifying Data PHP Exercises Assignment 1.
Creating a simple database This shows you how to set up a database using PHPMyAdmin (installed with WAMP)
Accessing mySQL relational database. MySQL database.  Today, we will attempt and open a connection to the MySQL server.  We need to specify the database.
Connecting, Queries, Best Practices Tran Anh Tuan Edit from Telerik Software Academy
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
Chapter 8 Manipulating MySQL Databases with PHP PHP Programming with MySQL 2 nd Edition.
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.
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.
The Web Wizard’s Guide to PHP by David Lash
Chapter 19 PHP Part III Credits: Parts of the slides are based on slides created by textbook authors, P.J. Deitel and H. M. Deitel by Prentice Hall ©
MySQL tutorial.
PHP and MySQL.
Erasmus Exchange in Ionian University
Web Programming– UFCFB Lecture
Database Access with PHP and MySQL
Presentation transcript:

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) NOT NULL, price DECIMAL(5,2) NOT NULL, description MEDIUMTEXT NOT NULL, PRIMARY KEY(rowID) )

Open/Close Connections mysql_connect() mysql_pconnect() mysql_close()

mysql_connect() resource mysql_connect ([string hostname [:port] [:/path/to/socket] [, string username] [, string password]]) <?php $link1 "webuser", "abcde") or die("Could not connect to MySQL server!"); $link2 "webuser", "secret") or die("Could not connect to MySQL server!"); ?>

mysql_pconnect() Works just like mysql_connect() except it checks to see if the connection is already open. If an open connection already exists it uses that connection instead of creating a new one.

mysql_close() boolean mysql_close ([resource link_id]) "webuser", "secret") or die("Could not connect to MySQL or die("Could not select database!"); echo "You're connected to a MySQL database!"; mysql_close(); ?>

Storing Connection Information in a Separate File Store the connect script in a separate header file or die("Could not connect to MySQL server!"); ?> This file can then be included as necessary, like so: <?php include "mysql.connect.php"; // begin database selection and queries. ?>

Securing Your Connection Information Use system-based user permissions to ensure that only the user owning the Web server daemon process is capable of reading the file. On Unix-based systems, this means changing the file ownership to that of the user running the Web process and setting the connection file permissions to -r If you’re connecting to a remote MySQL server, keep in mind that this information will be passed in plain text unless appropriate steps are taken to encrypt that data during transit. Your best bet is to use Secure Sockets Layer (SSL) encryption.

Choosing a Database mysql_select_db() boolean mysql_select_db (string db_name [, resource link_id]) "webuser", "secret") or die("Could not connect to MySQL or die("Could not select database!"); ?>

Querying MySQL mysql_query() mysql_db_query() Resource Identifier

mysql_query() resource mysql_query (string query, [resource link_id]) <?php /* Connect to MySQL server and select database. */ $linkID or die("Could not connect to MySQL or die("Could not select database"); /* Create and execute query. */ $query = "INSERT INTO product set productid='abcd123', name='pants', price='45.20'"; $result = mysql_query($query); /* Close connection to database server. */ mysql_close(); ?>

mysql_db_query() resource mysql_db_query (string database, string query [, resource link_id]) Works like mysql_query() except that database to be selected is passed as a parameter. <?php /* Connect to MySQL server and select database. */ $linkID or die("Could not connect to MySQL server"); /* Create and execute query. */ $query = "INSERT INTO product set productid='A0022JKL', name='pants', price='45.20'"; $result = mysql_db_query("company", $query); /* Close connection to database server. */ mysql_close(); ?>

Resource Identifier DESCRIBE, EXPLAIN, SELECT, and SHOW queries return a Resource Identifier on success and FALSE on failure ALL other queries TRUE on success and FALSE on failure The Resource Identifier can be passed to other functions that can provide information about the query

Retrieving and Displaying Data mysql_result() mysql_fetch_row() mysql_fetch_array() mysql_fetch_assoc()

mysql_result() mixed mysql_result (resource result_set, int row [, mixed field]) Retreives data from one filed of the specified row found in the result set. Simple but inefficient. Note in examples that – Row is specified as an offset – Field is identified by field name

mysql_result() cont. Find two values in a single row <?php... $query = "SELECT productid, name FROM product ORDER BY name"; $result = mysql_query($query); $productid = mysql_result($result, 0, "productid"); $name = mysql_result($result, 0, "name");... ?>

mysql_result() cont. Find all values (rows) of two fields <?php... $query = "SELECT productid, name FROM product ORDER BY name"; $result = mysql_query($query); // Loop through each row, outputting the productid and name for ($count=0; $count <= mysql_numrows($result); $count++) { $productid = mysql_result($result, $count, "productid"); $name = mysql_result($result, $count, "name"); echo "Product: $name ($productid) "; }... ?>

mysql_fetch_row() array mysql_fetch_row (resource result_set) Retrieves an entire row Places values in an indexed array

mysql_fetch_row() cont. <?php... $query = "SELECT productid, name FROM product ORDER BY name"; $result = mysql_query($query); while (list($productid, $name) = mysql_fetch_row($result)) { echo "Product: $name ($productid) "; }... ?> By using the list() function and a while loop, you can assign the field values to a variable as each row is encountered, foregoing the additional steps otherwise necessary to assign the array values to variables.

mysql_fetch_array() array mysql_fetch_array (resource result_set [,int result_type]) an enhanced version of mysql_fetch_row() result_type determines how data is retrieved – MYSQL_ASSOC: Returns the row as an associative array, with the key represented by the field name and the value by the field contents. – MYSQL_NUM: Returns the row as a numerically indexed array, with the ordering determined by the ordering of the field names as specified within the array. If an asterisk is used (signaling the query to retrieve all fields), the ordering will correspond to the field ordering in the table definition. Designating this option results in mysql_fetch_array() operating in the same fashion as mysql_fetch_row(). – MYSQL_BOTH: Returns the row as both an associative and a numerically indexed array. Therefore, each field could be referred to in terms of its index offset and its field name. This is the default.

mysql_fetch_array() cont. $query = "SELECT productid, name FROM product ORDER BY name"; $result = mysql_query($query); while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { $name = $row['name']; $productid = $row['productid']; echo "Product: $name ($productid) "; }

mysql_fetch_array() cont. $query = "SELECT productid, name FROM product ORDER BY name"; $result = mysql_query($query); while ($row = mysql_fetch_array($result, MYSQL_NUM)) { $name = $row[1]; $productid = $row[0]; echo "Product: $name ($productid) "; }

mysql_fetch_assoc() array mysql_fetch_assoc (resource result_set) Identical to mysql_fetch_array() when MYSQL_ASSOC is passed in as the result_type parameter.

Inserting Data Inserting data is similar to retrieving data except that the query often contains variable data. Two steps – Collect the data – Insert the data into the database Example – HTML form collects data – PHP script inserts data

HTML form insert (insert.php) " method="post"> Product ID: Name: Price: Description:

PHP code for the insert <?php // If the submit button has been pressed if (isset($_POST['submit'])) { // Connect to the server and select the database $linkID or die("Could not connect to MySQL or die("Could not select database"); // Retrieve the posted product information. $productid = $_POST['productid']; $name = $_POST['name']; $price = $_POST['price']; $description = $_POST['description']; // Insert the product information into the product table $query = "INSERT INTO product SET productid='$productid', name='$name', price='$price', description='$description'"; $result = mysql_query($query); // Display an appropriate message if ($result) echo " Product successfully inserted! "; else echo " There was a problem inserting the product! "; mysql_close(); } // Include the insertion form include "insert.php"; ?>

Modifying Data Similar to Inserting Three steps – Display existing data – Collect changes – Post changes Example – HTML form displays existing value – HTML form collects changes – PHP script inserts data

HTML form captures row to be modified. Choose a product: Apples Bananas Oranges

PHP code retrieves row & displays filled in form (modify.php) // If the form has been submitted if (isset($_POST['submit'])) { // Retrieve the posted rowID $rowID = $_POST['rowID']; // Select the product data based on the rowID $query = "SELECT name, productid, price, description FROM product WHERE rowID='$rowID'"; $result = mysql_query($query); // Assign the product information to variables list($name,$productid,$price,$description) = mysql_fetch_row($result); // Include the form where the product data will be populated include "modifyform.php"; }

HTML form (modifyform.php) " method="post"> "> Product ID: <input type="text" name="productid" size="8" maxlength="8" value=" " /> Name: <input type="text" name="name" size="25" maxlength="25" value=" " /> Price: <input type="text" name="price" size="6" maxlength="6" value=" " /> Description:

Update Example if (isset($_POST['submit'])) { // Assign the posted information to variables $rowID = $_POST['rowID']; $productid = $_POST['productid']; $name = $_POST['name']; $price = $_POST['price']; $description = $_POST['description']; // Update the database with the new product information $query = "UPDATE product SET productid='$productid', name='$name', price='$price', description='$description' WHERE rowID='$rowID'"; $result = mysql_query($query); // Inform the reader whether the update process was successful if ($result) echo " The product has been successfully updated. "; else echo " There was a problem updating the product. "; }

Deleting Data Similar to Modification Three steps – Display existing data – Select data to be deleted – Post changes Example – PHP script deletes data

Delete example <?php // Connect to the server and select the database mysql_connect("localhost","webuser","secret"); mysql_select_db("company"); // Has the form been submitted? if (isset($_POST['submit'])) { // Loop through each product with an enabled checkbox foreach($count=0; $count < count($_POST['rowID']); $count++) { $rowID = $_POST['rowID'][$count]; $query = "DELETE FROM product WHERE rowID='$rowID'"; $result = mysql_query($query); // Should have one affected row if ((mysql_affected_rows() == 0) || mysql_affected_rows() == -1) { echo " There was a problem deleting some of the selected items. "; exit; } echo " The selected items were successfully deleted. "; } ?>

mysql_num_rows() int mysql_num_rows (resource result_set) Return value is number of row that are returned by a SELECT query. Return value of -1 indicates query error. $query = "SELECT name FROM product WHERE price > 15.99"; $result = mysql_query($query); echo "There are ".mysql_num_rows($result)." product(s) priced above \$15.99.";

mysql_affected_rows() int mysql_affected_rows ([resource link_id]) Return value is number of rows affected by INSERT, UPDATE, or DELETE query. $query = "UPDATE product SET price = '39.99' WHERE price='34.99'"; $result = mysql_query($query); echo "There were ".mysql_affected_rows()." product(s) affected. ";

mysql_list_dbs() resource mysql_list_dbs ([resource link_id]) Retrieves the names of all databases found on the server. If link_id specified then databases for that server connection, otherwise most recently opened server connection.

mysql_db_name() string mysql_db_name (resource result_set, integer index) retrieves the name of the database located at position index

mysql_list_tables() resource mysql_list_tables (string database [, resource link_id]) Return the names of all tables in the database. <?php mysql_connect("localhost","webuser","secret"); $tables = mysql_list_tables("company"); while (list($table) = mysql_fetch_row($tables)) { echo "$table "; } ?>

mysql_tablename() string mysql_tablename (resource result_set, integer index) retrieves the name of the table located at position index <?php mysql_connect("localhost","webuser","secret"); $tables = mysql_list_tables("company"); $count = 0; while ($count < mysql_numrows($tables)) { echo mysql_tablename($tables,$count)." "; $count++; } ?>

mysql_fetch_field() object mysql_fetch_field (resource result [, int field_offset]) retrieves an object containing information pertinent to the field specified by field_offset Object properties are: – name – field name- multiple_key – table – field table- numeric – max_length- blob – not_null- type – primary_key- unsigned – unique_key- zerofill

mysql_fetch_field() example <?php mysql_connect("localhost","webuser","secret"); mysql_select_db("company"); $query = "SELECT * FROM product LIMIT 1"; $result = mysql_query($query); $fields = mysql_num_fields($result); for($count=0;$count<$fields;$count++) { $field = mysql_fetch_field($result,$count); echo " $field->name $field->type ($field->max_length) "; } ?>

mysql_num_fields() integer mysql_num_fields (resource result_set) returns the number of fields located in the result_set <?php... $query = "SELECT productid, name FROM product ORDER BY name"; $result = mysql_query($query); echo "Total number of fields returned: ".mysql_num_fields($result).". ";... ?>

mysql_list_fields() resource mysql_list_fields (string database_name, string table_name [, resource link_id]) retrieves the names of all fields located in table_name $fields = mysql_list_fields("company","product"); echo "Total number of fields returned: ".mysql_num_fields($fields).". ";

mysql_field_flags() string mysql_field_flags (resource result_set, integer field_offset) retrieves all options assigned to the field located in position field_offset of the result_set $query = "SELECT productid, name FROM product ORDER BY name"; $result = mysql_query($query); $row = mysql_fetch_row($result); echo mysql_field_flags($result, 0);

mysql_field_len() integer mysql_field_len (resource result_set, integer field_offset) retrieves the length of the field residing in the field_offset position of result_set $query = "SELECT description FROM product WHERE productid='tsbxxl'"; $result = mysql_query($query); $row = mysql_fetch_row($result); echo mysql_field_len($result, 0);

mysql_field_name() string mysql_field_name (resource result_set, int field_offset) returns the name of the field specified by the field_offset position of result_set $query = "SELECT productid as Product_ID, name FROM product ORDER BY name"; $result = mysql_query($query); $row = mysql_fetch_row($result); echo mysql_field_name($result, 0);

mysql_field_type() string mysql_field_type (resource result_set, int field_offset) returns the type of the field specified by the field_offset position of result_set $query = "SELECT productid, name FROM product ORDER BY name"; $result = mysql_query($query); $row = mysql_fetch_row($result); echo mysql_field_type($result, 0);

mysql_field_table() string mysql_field_table (resource result_set, int field_offset) returns the name of the table that contains the field specified by the field_offset position of result_set. $query = "SELECT productid as Product_ID, name FROM product ORDER BY name"; $result = mysql_query($query); $row = mysql_fetch_row($result); echo mysql_field_table($result, 0);

Viewing Table Properties <?php mysql_connect("localhost","webuser","secret"); // The view_db_properties() function retrieves table information for // the database defined by the input parameter $db, and invokes // view_table_properties() for each table instance located within // that database. function view_db_properties($db) { mysql_select_db($db); $tables = mysql_list_tables($db); while (list($tableName) = mysql_fetch_row($tables)) { echo " Table: $tableName "; echo " "; echo " Field Type Length Flags "; echo view_table_properties($tableName); echo " "; }

Viewing Table Properties (cont) // The view_table_properties() function retrieves // field properties for the table defined by the input parameter $table. */ function view_table_properties($table) { $tableRows = ""; // Retrieve a single row from the table, // giving us enough field information to determine field properties. $result = mysql_query("SELECT * FROM $table LIMIT 1"); $fields = mysql_num_fields($result); for($count=0; $count < $fields; $count++) { // Retrieve field properties $name = mysql_field_name($result,$count); $type = mysql_field_type($result,$count); $length = mysql_field_len($result,$count); $flags = mysql_field_flags($result,$count); $tableRows.= " $name $type $length $flags "; } return $tableRows; } view_db_properties("company"); ?>