Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lec_6 Manipulating MySQL Databases with PHP PHP Programming with MySQL.

Similar presentations


Presentation on theme: "Lec_6 Manipulating MySQL Databases with PHP PHP Programming with MySQL."— Presentation transcript:

1 Lec_6 Manipulating MySQL Databases with PHP PHP Programming with MySQL

2 2 www.BZUpages.com PHP Programming with MySQL www.BZUpages.com Opening a MySQL Connection Open a connection to a MySQL database with mysqli_connect() –Returns a positive integer if connection is successful –Returns false if it is not Assign the return value to a variable –$connection = mysqli_connect("host"[, "user ", "password", "database"]) –host specifies where MySQL database server resides –user and password specify MySQL username and password –database selects a database with which to work

3 3 www.BZUpages.com PHP Programming with MySQL www.BZUpages.com Selecting a Database Select a database when connecting OR Use mysqli_select_db() function Syntax –mysqli_select_db(connection, database) –Use connection variable returned by mysqli_connect() Return value –True if database is selected successfully –False if it is not Also enables you to change current database

4 4 www.BZUpages.com PHP Programming with MySQL www.BZUpages.com Closing a Database Connection Any open database connections are closed automatically when a PHP script ends. Should be closed explicitly when you are finished with the connection –Releases memory mysqli_close($connection)

5 5 www.BZUpages.com PHP Programming with MySQL www.BZUpages.com Example $connect = mysqli_connect(“localhost”, “tostrand”, “tjo123”); mysqli_select_db($connect, “e-commerce”); mysqli_close($connect);

6 6 www.BZUpages.com PHP Programming with MySQL www.BZUpages.com Handling MySQL Errors Reasons for failure to connect to a database server include: –The database server is not running –Insufficient privileges to access the data source –Invalid username and/or password

7 7 www.BZUpages.com PHP Programming with MySQL www.BZUpages.com Suppressing Errors with the Error Control Operator Writing code that anticipates and handles potential problems is called bulletproofing Bulletproofing techniques include: –Validating submitted form data –Using the error control operator (@) to suppress error messages –Providing your own custom (user-friendly) error messages

8 8 www.BZUpages.com PHP Programming with MySQL www.BZUpages.com Terminating Script Execution The die() function terminates script execution Accepts a single string argument Call the die() as a separate statement OR Append the function call to an expression with the Or operator

9 9 www.BZUpages.com PHP Programming with MySQL www.BZUpages.com Terminating Script Execution $DBConnect = @mysqli_connect("localhost", "root", "paris"); if (!$DBConnect) die("The db server is not available. "); echo "Successfully connected to the db server. "; $DBSelect = @mysqli_select_db($DBConnect, "flightlog"); if (!$DBSelect) die("The database is not available. "); echo "Successfully opened the database. "; // additional statements that access the database mysqli_close($DBConnect);

10 10 www.BZUpages.com PHP Programming with MySQL www.BZUpages.com Terminating Script Execution $DBConnect = @mysqli_connect("localhost", "dongosselin", "rosebud") Or die("The db server is not available. "); echo "Successfully connected to the db server. "; @mysqli_select_db($DBConnect, "flightlog") Or die("The database is not available. "); echo "Successfully opened the database. "; // additional statements that access the database server mysqli_close($DBConnect);

11 11 www.BZUpages.com PHP Programming with MySQL www.BZUpages.com MySQL Error Reporting Functions

12 12 www.BZUpages.com PHP Programming with MySQL www.BZUpages.com Reporting MySQL Errors $User = $_GET['username']; $Password = $_GET['password']; $DBConnect = @mysqli_connect("localhost", $User, $Password) Or die("Unable to connect to the database server. ". "Error code ". mysqli_connect_errno(). ": ". mysqli_connect_error()). " "; echo "Successfully connected to the database server. "; @mysqli_select_db($DBConnect, "flightlog") Or die("Unable to select the database. ". "Error code ". mysqli_errno($DBConnect). ": ". mysqli_error($DBConnect)). " "; echo "Successfully opened the database. "; // additional statements mysqli_close($DBConnect);

13 13 www.BZUpages.com PHP Programming with MySQL www.BZUpages.com Executing SQL Statements mysqli_query() function sends SQL statements to MySQL database mysqli_query(connection, query) Returns one of three values: –For SQL statements that do not return results (e.g. CREATE TABLE, INSERT ), returns true if the statement executes successfully –For SQL statements that return results (e.g. SELECT ), returns a result pointer that represents the query results Refers to the currently selected row in a resultset –Returns false for any SQL statements that fail, regardless of whether they return results

14 14 www.BZUpages.com PHP Programming with MySQL www.BZUpages.com Working with Query Results mysqli_fetch_row() –returns fields in the current row into an indexed array mysqli_fetch_assoc() –returns fields in the current row into an associative array mysqli_fetch_array() –returns fields in the current row into an indexed array or associative array

15 15 www.BZUpages.com PHP Programming with MySQL www.BZUpages.com mysqli_fetch_row() Returns the fields in the current row of a resultset into an indexed array Moves the result pointer to the next row echo " "; echo " Make Model Price Quantity "; $Row = mysqli_fetch_row($QueryResult); do { echo " {$Row[0]} "; echo “ {$Row[1]} "; echo “ {$Row[2]} "; echo “ {$Row[3]} "; $Row = mysqli_fetch_row($QueryResult); } while ($Row);

16 16 www.BZUpages.com PHP Programming with MySQL www.BZUpages.com

17 17 www.BZUpages.com PHP Programming with MySQL www.BZUpages.com mysqli_fetch_assoc() The function returns the fields in the current row of a resultset into an associative array Moves the result pointer to the next row Each field name is used as an array key echo " "; echo " Make Model Price Quantity "; do { $Row = mysqli_fetch_assoc($QueryResult); echo " {$Row[‘make’]} "; echo “ {$Row[‘model’]} "; echo “ {$Row[‘price’]} "; echo “ {$Row[‘quantity’]} "; $Row = mysqli_fetch_row($QueryResult); } while ($Row);

18 18 www.BZUpages.com PHP Programming with MySQL www.BZUpages.com Accessing Query Result Information mysqli_num_rows() returns the number of rows in a query result mysqli_num_fields() returns the number of fields in a query result Both functions accept a database connection variable as an argument

19 19 www.BZUpages.com PHP Programming with MySQL www.BZUpages.com $SQLstring = "SELECT * FROM inventory"; $QueryResult = @mysqli_query($DBConnect, $SQLstring) Or die("Unable to execute the query. ". "Error code “. mysqli_errno($DBConnect). ": ". mysqli_error($DBConnect)). " "; echo "Successfully executed the query. "; $NumRows = mysqli_num_rows($QueryResult); $NumFields = mysqli_num_fields($QueryResult); if ($NumRows != 0 && $NumFields != 0) echo "Your query returned ". mysqli_num_rows($QueryResult). " rows and ". mysqli_num_fields($QueryResult). " fields. "; else echo "Your query returned no results. "; mysqli_close($DBConnect);

20 20 www.BZUpages.com PHP Programming with MySQL www.BZUpages.com

21 21 www.BZUpages.com PHP Programming with MySQL www.BZUpages.com Closing Query Results When you are finished working with query results, use the mysqli_free_result() function to close the resultset. Takes query result as a parameter –mysqli_free_result($queryResult); Only works when the SQL statement returns results.

22 22 www.BZUpages.com PHP Programming with MySQL www.BZUpages.com Creating Databases Use the CREATE DATABASE statement with the mysqli_query() function to create a new database Use mysqli_db_select() to check whether a database exists before you create or delete it To use a new database, select it by executing the mysqli_select_db() function Use the DROP DATABASE statement with the mysqli_query() function to delete a database

23 23 www.BZUpages.com PHP Programming with MySQL www.BZUpages.com $DBName = "real_estate";... if (@mysqli_select_db($DBConnect, $DBName)) echo "The $DBName database already exists! "; else { $SQLstring = “CREATE DATABASE $DBName"; $QueryResult = @mysqli_query($DBConnect, $SQLstring) Or die("Unable to execute the query. ". "Error code “. mysqli_errno($DBConnect). ": “. mysqli_error($DBConnect)). " "; echo "Successfully created the database. "; mysqli_select_db($DBConnect, $DBName); }

24 24 www.BZUpages.com PHP Programming with MySQL www.BZUpages.com Creating Tables To create a table, use the CREATE TABLE statement with the mysqli_query() function Execute the mysqli_select_db() function before executing the CREATE TABLE statement –Prevents the new table from being created in the wrong database Use mysqli_query() to ensure that the table doesn’t already exist

25 25 www.BZUpages.com PHP Programming with MySQL www.BZUpages.com $DBName = "real_estate";... $SQLstring = "CREATE TABLE commercial (city VARCHAR(25), state VARCHAR(25), sale_or_lease VARCHAR(25), type_of_use VARCHAR(40), price INT, size INT)"; $QueryResult = @mysqli_query($DBConnect, $SQLstring) Or die("Unable to execute the query. ". "Error code ". mysqli_errno($DBConnect). ": ". mysqli_error($DBConnect)). " "; echo "Successfully created the table. "; mysqli_close($DBConnect);

26 26 www.BZUpages.com PHP Programming with MySQL www.BZUpages.com Adding Records To add records to a table, use an INSERT statement with the mysqli_query() function –INSERT INTO tableName VALUES (val1, val2, val3…) The values entered in the VALUES list must be in the same order as the table fields Specify NULL in any fields for which you do not have a value –Field definition must allow NULL values or an error will occur

27 27 www.BZUpages.com PHP Programming with MySQL www.BZUpages.com Updating Records To update records in a table, use an UPDATE statement with the mysqli_query() function The WHERE keyword determines which records to update in the table –UPDATE tableName SET field = value WHERE condition; –UPDATE books SET title = “PHP Made Simple” WHERE isbn = ‘123-45-6889’;

28 28 www.BZUpages.com PHP Programming with MySQL www.BZUpages.com Deleting Records To delete records in a table, use a DELETE statement with the mysqli_query() function The WHERE keyword determines which records to delete in the table –DELETE FROM tableName WHERE condition; –DELETE FROM books WHERE isbn = ‘123-45-6889’;

29 29 www.BZUpages.com PHP Programming with MySQL www.BZUpages.com More Functions mysqli_num_rows() –Find the number of records returned from a SELECT query mysqli_affected_rows() –Determine the number of rows affected by an INSERT, UPDATE or DELETE query

30 30 www.BZUpages.com PHP Programming with MySQL www.BZUpages.com $SQLstring = "UPDATE inventory SET price=368.20 WHERE make='Fender' AND model='DG7'"; $QueryResult = @mysqli_query($DBConnect, $SQLstring) Or die("Unable to execute the query. ". "Error code ". mysqli_errno($DBConnect). ": ". mysqli_error($DBConnect)). " "; echo "Successfully updated ". mysqli_affected_rows($DBConnect). " record(s). ";


Download ppt "Lec_6 Manipulating MySQL Databases with PHP PHP Programming with MySQL."

Similar presentations


Ads by Google