Presentation is loading. Please wait.

Presentation is loading. Please wait.

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)

Similar presentations


Presentation on theme: "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)"— Presentation transcript:

1 PHP – MySQL Extensions

2 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) )

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

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

5 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.

6 mysql_close() boolean mysql_close ([resource link_id]) <?php @mysql_connect("localhost", "webuser", "secret") or die("Could not connect to MySQL server!"); @mysql_select_db("company") or die("Could not select database!"); echo "You're connected to a MySQL database!"; mysql_close(); ?>

7 Storing Connection Information in a Separate File Store the connect script in a separate header file <?php @mysql_connect("localhost","webuser","secret") 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. ?>

8 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.

9 Choosing a Database mysql_select_db() boolean mysql_select_db (string db_name [, resource link_id]) <?php @mysql_connect("localhost", "webuser", "secret") or die("Could not connect to MySQL server!"); @mysql_select_db("company") or die("Could not select database!"); ?>

10 Querying MySQL mysql_query() mysql_db_query() Resource Identifier

11 mysql_query() resource mysql_query (string query, [resource link_id]) <?php /* Connect to MySQL server and select database. */ $linkID = @mysql_connect("localhost","webuser","secret") or die("Could not connect to MySQL server"); @mysql_select_db("company") 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(); ?>

12 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 = @mysql_connect("localhost","webuser","secret") 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(); ?>

13 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

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

15 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

16 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");... ?>

17 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) "; }... ?>

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

19 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.

20 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.

21 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) "; }

22 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) "; }

23 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.

24 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

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

26 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 = @mysql_connect("localhost","webuser","secret") or die("Could not connect to MySQL server"); @mysql_select_db("company") 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"; ?>

27 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

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

29 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"; }

30 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:

31 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. "; }

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

33 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. "; } ?>

34 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.";

35 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. ";

36 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.

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

38 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 "; } ?>

39 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++; } ?>

40 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

41 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) "; } ?>

42 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).". ";... ?>

43 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).". ";

44 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);

45 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);

46 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);

47 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);

48 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);

49 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 " "; }

50 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"); ?>


Download ppt "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)"

Similar presentations


Ads by Google