Chapter 5 PHP and MySQL Lectured by: Nguyễn Hữu Hiếu Objectives In this lesson, 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 Trường Đại Học Bách Khoa TP.HCM 2 Web Lập Trình Khoa Khoa Học và Kỹ Thuật Máy Tính 2 © 2020 Connecting to MySQL with PHP • PHP has the ability to access and manipulate any database that is ODBC (Open Database Connectivity) compliant • PHP includes functionality that allows you to work directly with different types of databases, without going through ODBC Trường Đại Học Bách Khoa TP.HCM 3 Web Lập Trình Khoa Khoa Học và Kỹ Thuật Máy Tính 3 © 2020 Which MySQL Package to Use • The mysqli (MySQL Improved) package became available with PHP 5 and is designed to work with MySQL version 4.3 and later • Earlier versions must use the mysql package • The mysqli package is the object-oriented equivalent of the mysql package but can also be used procedurally • Mysqli package has improved speed, security and compatibility with libraries. Trường Đại Học Bách Khoa TP.HCM 4 Web Lập Trình Khoa Khoa Học và Kỹ Thuật Máy Tính 4 © 2020 Opening and Closing a Connection • Open a connection to a MySQL database server with the mysqli_connect() function • The mysqli_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 mysqli_connect() function to a variable that you can use to access the database in your script Trường Đại Học Bách Khoa TP.HCM 5 Web Lập Trình Khoa Khoa Học và Kỹ Thuật Máy Tính 5 © 2020 Opening and Closing a Connection • The syntax for the mysqli_connect() function is: $connection = mysqli_connect("host" [, "user", "password"[,”database”]]); • 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 • You can optionally select the database when connecting. Trường Đại Học Bách Khoa TP.HCM 6 Web Lập Trình Khoa Khoa Học và Kỹ Thuật Máy Tính 6 © 2020 Opening and Closing a Connection • The database connection is assigned to the $DBConnect variable $DBConnect = mysqli_connect("localhost", "billyeakus ", "hotdog"); • Close a database connection using the mysql_close() function mysqli_close($DBConnect); Trường Đại Học Bách Khoa TP.HCM 7 Web Lập Trình Khoa Khoa Học và Kỹ Thuật Máy Tính 7 © 2020 Opening and Closing a Connection mysqli_get_client_info() Returns the MySQL client library version mysqli_get_client_stats() Returns statistics about client per-process mysqli_get_client_version() Returns the MySQL client library version as an integer mysqli_get_connection_stats() Returns statistics about the client connection mysqli_get_host_info() Returns the MySQL server hostname and the connection type mysqli_get_proto_info() Returns the MySQL protocol version mysqli_get_server_info() Returns the MySQL server version mysqli_get_server_version() Returns the MySQL server version as an integer Trường Đại Học Bách Khoa TP.HCM 8 Web Lập Trình Khoa Khoa Học và Kỹ Thuật Máy Tính 8 © 2020 Opening and Closing a Connection version.php in a Web browser Trường Đại Học Bách Khoa TP.HCM 9 Web Lập Trình Khoa Khoa Học và Kỹ Thuật Máy Tính 9 © 2020 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 Trường Đại Học Bách Khoa TP.HCM 10 Web Lập Trình Khoa Khoa Học và Kỹ Thuật Máy Tính 10 © 2020 Reporting MySQL Errors • The mysqli_errno() function returns the error code from the last attempted MySQL function call or 0 if no error occurred • The mysqli_error() — Returns the text of the error message from previous MySQL operation • The mysqli_errno() and mysqli_error() functions return the results of the previous mysqli*() function Trường Đại Học Bách Khoa TP.HCM 11 Web Lập Trình Khoa Khoa Học và Kỹ Thuật Máy Tính 11 © 2020 Selecting a Database • The syntax for the mysqli_select_db() function is: mysqli_select_db(connection, database); • 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 Trường Đại Học Bách Khoa TP.HCM 12 Web Lập Trình Khoa Khoa Học và Kỹ Thuật Máy Tính 12 © 2020 Sample Code good $link = mysqli_connect("cs.edu", “demo", “demo"); mysqli_select_db($link, "nonexistentdb”); bad echo mysql_errno($link). "<br>"; mysqli_select_db( $link, “demo"); good mysqli_query($link, bad "SELECT * FROM nonexistenttable"); echo mysqli_errno($link).
"<br>"; Trường Đại Học Bách Khoa TP.HCM 13 Web Lập Trình Khoa Khoa Học và Kỹ Thuật Máy Tính 13 © 2020 Sample Code $host='localhost'; $userName = 'demo'; $password = 'demo'; $database ='demo'; $link = mysqli_connect ($host, $userName, $password) ; if (!$link) { die('Could not connect: '. mysqli_error($link)); } echo 'Connected successfully'; mysqli_close($link); Trường Đại Học Bách Khoa TP.HCM 14 Web Lập Trình Khoa Khoa Học và Kỹ Thuật Máy Tính 14 © 2020 include(‘file.php’); include_once(‘file.php’) require(‘file.php’); require_once(‘file.php <?php include_once(‘config/file.php’); echo “test”; include(‘config/file.php’); ?> config/file.php <?php include(‘file2.php’); ?> Trường Đại Học Bách Khoa TP.HCM Lập Trình Web Khoa Khoa Học và Kỹ Thuật Máy Tính 15 © 2020 Sample Code <?php $link = mysqli_connect('localhost', 'mysql_user', 'mys ql_password'); if (!$link) { die('Not connected : '. mysqli_error($link)); } // make foo the current db $db_selected = mysqli_select_db($link,'foo'); if (!$db_selected) { die ('Can\'t use foo : '. mysqli_error($link)); } ?> Trường Đại Học Bách Khoa TP.HCM 16 Web Lập Trình Khoa Khoa Học và Kỹ Thuật Máy Tính 16 © 2020 Executing SQL Statements • Use the mysqli_query() function to send SQL statements to MySQL • The syntax for the mysqli_query() function is: mysqli_query(connection, query); • The mysqli_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 Trường Đại Học Bách Khoa TP.HCM 17 Web Lập Trình Khoa Khoa Học và Kỹ Thuật Máy Tính 17 © 2020 Executing SQL Statements – For SQL statements that return results (SELECT and SHOW statements) the mysqli_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 mysqli_query() function returns a value of FALSE for any SQL statements that fail, regardless of whether they return results Trường Đại Học Bách Khoa TP.HCM 18 Web Lập Trình Khoa Khoa Học và Kỹ Thuật Máy Tính 18 © 2020 Sample Code <?php // This could be supplied by a user, for example $firstname = 'fred'; $lastname = 'fox'; //never trust user data $firstname= mysql_real_escape_string($firstname); $lastname= mysql_real_escape_string($lastname); // Formulate Query // For more examples, see mysql_real_escape_string() $query = "SELECT firstname, lastname, address, age FROM friends WHERE firstname=‘$firstname ‘ AND lastname= ‘$lastname’”; // Perform Query $result = mysql_query($query); // Check result // This shows the actual query sent to MySQL, and the error.
Useful for debugging. if (!$result) { $message = 'Invalid query: '. $query; die($message); } // Use result // Attempting to print $result won't allow access to information in the resource // One of the mysql result functions must be used // See also mysql_fetch_array(), mysql_fetch_row(), etc. while ($row = mysql_fetch_assoc($result)) { echo $row['firstname']; echo $row['lastname']; echo $row['address']; echo $row['age']; } // Free the resources associated with the result set // This is done automatically at the end of the script mysql_free_result($result); ?> Trường Đại Học Bách Khoa TP.HCM 19 Web Lập Trình Khoa Khoa Học và Kỹ Thuật Máy Tính 19 © 2020 Adding, Deleting, and Updating Records • To add records to a table, use the INSERT and VALUES keywords with the mysqli_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 Trường Đại Học Bách Khoa TP.HCM 20 Web Lập Trình Khoa Khoa Học và Kỹ Thuật Máy Tính 20 © 2020 Adding, Deleting, and Updating Records <?php $con = mysqli_connect("localhost","demo","demo"); if (!$con) { die('Could not connect: '.
mysqli_error($con)); } mysqli_select_db($con, "demo"); mysqli_query($con, "INSERT INTO friends (FirstName, LastName, Age) VALUES ('Lester', 'Longbottom', '35')"); mysqli_query($con,"INSERT INTO friends (FirstName, LastName, Age) VALUES ('Carly', 'Sampson', '33')"); mysqli_close($con); ?> Trường Đại Học Bách Khoa TP.HCM Lập Trình Web Khoa Khoa Học và Kỹ Thuật Máy Tính 21 © 2020 Adding, Deleting, and Updating Records • 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 mysqli_query() function • Omit the WHERE clause to delete all records in a table Trường Đại Học Bách Khoa TP.HCM 22 Web Lập Trình Khoa Khoa Học và Kỹ Thuật Máy Tính 22 © 2020 Adding, Deleting, and Updating Records ?php $con = mysqli_connect("localhost","demo","demo"); if (!$con) { die('Could not connect: '. mysqli_error($con)); } mysqli_select_db($con,"demo"); mysqli_query($con,"UPDATE friends SET Age = '61' WHERE FirstName = 'Bill' AND LastName = 'Yeakus'"); mysqli_close($con); ?> Trường Đại Học Bách Khoa TP.HCM Lập Trình Web Khoa Khoa Học và Kỹ Thuật Máy Tính 23 © 2020 Retrieving Records into an Indexed Array The mysqli_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 "<table border=1>"; echo "<tr><th>First</th><th>Last</th> <th>Address</th><th>age</th></tr>"; $Row = mysqli_fetch_row($result); do { echo "<tr><td>{$Row[0]}</td>"; echo "<td>{$Row[1]}</td>"; echo "<td>{$Row[2]}</td>"; echo "<td>{$Row[3]}</td></tr>"; $Row = mysqli_fetch_row($result); } while ($Row); echo "</table>"; mysqli_close($con); ?> Trường Đại Học Bách Khoa TP.HCM 24 Web Lập Trình Khoa Khoa Học và Kỹ Thuật Máy Tính 24 © 2020 Sample Code <?php $con = mysqli_connect("localhost","demo","demo","demo"); if (!$con) { die('Could not connect: '. mysqli_error($con)); } $q = "SELECT * FROM friends"; $result = mysqli_query($con,$q); echo "<table border=1>"; echo "<tr><th>First</th><th>Last</th> <th>Address</th><th>age</th></tr>"; while ($Row=mysqli_fetch_assoc($result)) { echo "<tr><td>{$Row['firstname']}</td>"; echo "<td>{$Row['lastname']}</td>"; echo "<td>{$Row['address']}</td>"; echo "<td>{$Row['age']}</td></tr>"; } echo "</table>"; mysqli_close($con); ?> Trường Đại Học Bách Khoa TP.HCM 25 Web Lập Trình Khoa Khoa Học và Kỹ Thuật Máy Tính 25 © 2020 Using the mysqli_affected_rows() Function • With queries that return results (SELECT queries), use the mysqli_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 mysqli_affected_rows() function to determine the number of affected rows Trường Đại Học Bách Khoa TP.HCM 26 Web Lập Trình Khoa Khoa Học và Kỹ Thuật Máy Tính 26 © 2020 Using the mysql_affected_rows() Function $QueryResult = mysqli_query($con,"UPDATE friends SET Age = '67' WHERE FirstName = 'Bill' AND LastName = 'Yeakus'"); if ($QueryResult === FALSE) echo "<p>Unable to execute the query. "</p>"; else echo "<p>Successfully updated ".
mysqli_affected_rows($con) .</p>"; mysql_close($con); ?> Trường Đại Học Bách Khoa TP.HCM 27 Web Lập Trình Khoa Khoa Học và Kỹ Thuật Máy Tính 27 © 2020 Using the mysql_affected_rows() Function Output of mysql_affected_rows() function for an UPDATE query Trường Đại Học Bách Khoa TP.HCM 28 Web Lập Trình Khoa Khoa Học và Kỹ Thuật Máy Tính 28 © 2020 Using the mysqli_info() Function • For queries that add or update records, or alter a table’s structure, use the mysqli_info() function to return information about the query • The mysqli_info() function returns the number of operations for various types of actions, depending on the type of query • The mysqli_info() function returns information about the last query that was executed on the database connection Trường Đại Học Bách Khoa TP.