What is MySQL? PHP Penn Wu, PhD 323. SELECT FROM Orders WHERE Amount > 200; Client browser. MySQL server. Apache server.

Size: px
Start display at page:

Download "What is MySQL? PHP Penn Wu, PhD 323. SELECT FROM Orders WHERE Amount > 200; Client browser. MySQL server. Apache server."

Transcription

1 Lecture #12 Introduction PHP and MySQL (MariaDB) PHP and MySQL is probably the most popular combination for building data-driven web sites. While PHP is a scripting language for building dynamic web applications, MySQL is an opensource relational database management system (RDBMS) with SQL being the abbreviation for Structured Query Language. A date-driven web site, built by the combination of PHP and MySQL, requires programmers to write PHP codes with PHP s MySQL API to interact with the MySQL server. The PHP interpreter extract the so-called SQL statement from the PHP script, access the designated MySQL server, and then maintain a connection for data to be sent from the MySQL server to the web server (typically Apache). The web server will organize the data in HTML format and pass only the HTML-version of content to the client browser. The following illustrates the flow. Client browser Apache server PHP interpreter MySQL server The following explains their relationships: HTML client-side layout Web server access control and contact window between client browser and PHP interpreter PHP code intermediary between web server and MySQL server MySQL server the source of data By the way, this lecture comes with three sample MySQL databases: Customers, Clients, and Endusers. Details about these databases are available at Appendix A. What is MySQL? MySQL was developed by Michael Widenius and David Axmark in Its source code is available under the terms of the GNU General Public License; therefore, it is free for use since its debut. However, in January 2008, Sun Microsystems bought MySQL for $1 billion, and then Oracle Corporation acquired Sun Microsystems in April 2009; therefore the ownership transferred to Oracle. Since Oracle s acquisition made MySQL becoming proprietary, developers of MySQL formed a developer community and began releasing MariaDB. MariaDB is based on the same code base as MySQL server 5.5 and aims to maintain compatibility with Oracle-owned MySQL version. Seeing that MariaDB s API and protocol are compatible with those used by MySQL, and XAMPP adopts MariaDB in its 7.xx version, the instructor decided to discuss how to access MySQL with PHP scripts by actually using MariaDB as the substitute of MySQL. MariaDB (and MySQL) only process SQL statements. Structured Query Language (SQL) is a special-purpose programming language designed to communicate with a database. SQL statements excute queries to retrieve data, insert records, update data, delete records as well as create and maintain a new database and components of a database, such as tables. The following is simple SQL statement that runs a query to retrieve data from a table named orders with a criteria amount is greater than 200. It is necessary to note that SQL is a not a case-sensitive language. SELECT FROM Orders WHERE Amount > 200; In this lecture, the instructor plans to use the following SQL commands. Again all SQL commands are not case sensitive. Both CREATE TABLE and create table work. In the PHP Penn Wu, PhD 323

2 following table, the instructor purposely uses uppercase to distinguish SQL commands from other components (such as tablename). Command CREATE DATABASE databasename CREATE TABLE tablename SELECT FROM tablename INSERT INTO tablename DROP TABLE tablename UPDATE tablename SET DELETE FROM tablename Description creates a new database creates a new table extracts data from a database inserts new data into a database deletes a table updates data in a database deletes data from a database A table of a database in a MariaDB server is a two-dimensional structure that has columns and rows. Each column consists of data of the same type and format, and is also known as field. In the following example, CID, name, address are example of fields. Each row consists of data of exactly the same entity. A row contains a record. In the following example, 101, 23 Workhaven Lan, 90630, , and Long Beach are records of Mike Smith CID name address zip code phone city Mike Smith 23 Workhaven Lane Long Beach 102 Ann McDonald 1411 Lillydale Drive Woodridge All versions of MySQL and MariaBD support command-line access. Programmers can use a shell like Microsoft's Command Prompt to access the shell by calling the mysql command, after the MySQL server is launched. In Windows operating systems, the file name is mysql.exe. Throughout this lecture, students will launch MySQL server with XAMPP Control Panel. In XAMPP, the mysql.exe file is placed in the X:\xampp\mysql\bin directory (where X is the drive name). With the MySQL up and running, the following is a sample statement that sets the path of the mysql.exe file. X:\>path=%path%;%CD%xampp\mysql\bin; After the path is set, use the following statement to log in to the MySQL with the root. The root account is the most privileged account on a Linux/Unix system. MySQL adopts this convention because it was originally created for running in Linux-based server. X:\>mysql -u root p When being prompt for password, simply press [Enter] to ignore the password requirement unless a password has been set. According to the MySQL document, if you have never assigned a root password for MySQL, the server does not require a password at all for connecting as root. Enter password: After logging in, the MySQL or MariaDB prompt appears. The following is the sample MariaDB prompt. PHP Penn Wu, PhD 324

3 Welcome to the MariaDB monitor. Commands end with ; or \g. Your MariaDB connection id is 2 Server version: MariaDB mariadb.org binary distribution Copyright (c) 2000, 2016, Oracle, MariaDB Corporation Ab and others. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. MariaDB [(none)]> The following uses the show databases; statement to demonstrate how to list all the available databases on the current MySQL server. MariaDB [(none)]> show databases; Database customers information_schema mysql performance_schema phpmyadmin rows in set (0.18 sec) MariaDB [(none)]> The use databasename; statement (where databasename must be an existing database) can select a specific database to use. The following demonstrates how to use a database named Customers. MariaDB> use customers; Database changed What is MySQLi? While popularity of MySQL is slowly moving toward MariaDB, PHP developers also introduced a new set of MySQL-based functions called MySQLi with i literally meaning improved. MySQLi is an extension for PHP, introduced in PHP 5.0, to replace previously available MySQLbased functions. According the PHP document, MySQLi has the following advantages: It s object-oriented interface and traditional procedural coding approach, making it easier to use Support for prepared statements, helping secure you code Support for multiple statements, allowing you to run more than one query at a time In order for PHP programmers to access a MariaDB (or MySQL) server, the programmers can know the following items, and all these items must exist and have been given appropriate user privilege (including access rights). serverid: This is the identifier of the MySQL (or MariaDB) server. Frequently, it is the hostname of the web server, such pbs.org or cnn.com. In the case of XAMPP, the default is localhost. Throughout this lecture, localhost is the server id. userid: This is the user id created by the MySQL server administrator for accessing the MySQL server. psd: This is the password associated with the above user id. dname: This is the identifier to be accessed, such as Customers. PHP Penn Wu, PhD 325

4 port: This is an optional parameter. If not assigned, the value is automatically set to By default, MySQL server uses port However, the network administrator might choose to use a different port, such as The following is a sample statement that builds a connection with a MariaDB server using the object oriented method. It calls the myqli() constructor of the mysqli class to create an instance. In the PHP developer document, the constructor is denoted as: mysqli:: construct(parameter). Once the instance, $conn, is created, it can use the $objectid->propertyname and $objectid->methodname() format to access all properties provided by the mysqli class. $conn = new mysqli(serverid, userid, psd, dname, port); The following is a statement that adopts the procedural method. The mysqli_connect() function opens a new connection to the MySQL server. $conn = mysqli_connect(serverid, userid, psd, dname, port); Seeing that MySQLi is the replacement for the PHP s mysql-based functions, and functions of MySQLi are said by PHP developers to have better and secured performance, plus PHP7 actually removed the old MySQL API and adopt only MySQLi, the instructor decided to discuss only MySQLi in this lecture. The next few chapters will discuss the most frequently used MySQLi functions. Accessing MySQL server from a PHP script A PHP script must connect to a database before performing any data operation. As stated in the previous section, both the mysqli() constructor of the mysqli class and the mysqli_connect() function is a procedural function can be used for connecting to MySQL. However, the mysqli() constructor only returns an object which represents the connection to a MySQL Server. Starting from PHP 5.3.0, whether or not there is a connection error is an issue handled by the connect_error property of the mysqli class. This property stores a string description of the last connect error (if any). The following is a sample template structure used by the instructor to decide if the connection has an error. If an error exists, immediately uses the die() function to display a message and immediately exit the current script. The message for the die() function to display is the error description stored in the connect_error property. The host_info property returns a string representing the type of connection used. The close() method of the mysqli class closes an opened database connection. By the way, be sure to read Preparation #1 and Preparation #2 before testing all the scripts in this lecture. $conn = new mysqli('localhost', 'tcm159', 'sgky4651', 'Customers'); if ($conn->connect_error) die($conn->connect_errno. ': '. $conn->connect_error); echo 'Success... '. $conn->host_info. "<br>"; $conn->close(); PHP Penn Wu, PhD 326

5 The following is a sample error message. Can t connect to MySQL server on localhost However, in practice, it is not a good idea to show the error message to the viewers. Most programmers choose to display a customized error message. die("attempt to build connection failed!"); Prior to PHP 5.3.0, programmers must call the mysqli_connect_error() function to get an error description from the last connection error. The mysqli_get_host_info() function returns the MySQL server hostname and the connection type. The mysqli_close() function closes an opened database connection. $conn = mysqli_connect('localhost', 'tcm159', 'sgky4651', 'Customers'); if (mysqli_connect_error()) die(mysqli_connect_errno(). ': '. mysqli_connect_error()); echo 'Success... '. mysqli_get_host_info($conn). "\n"; mysqli_close($conn); Some programmers prefer not to disclose the error information. They simply use the die() function to display a generic error message, as shown below. Object-oriented if ($conn->connect_error) die("connection failed."); Procedural if (mysqli_connect_error()) die("connection failed."); According to the PHP document, the mysqli_connect() function is a Boolean type; therefore, it could return TRUE of FALSE to indicate success or failure of the connection. The above code can be simplified to: $conn = mysqli_connect('localhost', 'tcm159', 'sgky4651', 'Customers'); if (!$conn) die(mysqli_connect_errno(). ': '. mysqli_connect_error()); echo 'Success... '. mysqli_get_host_info($conn). "\n"; mysqli_close($conn); PHP Penn Wu, PhD 327

6 The mysqli_close() method will close an opened connection and release all resources dedicated to that connection. It is a good practice to always explicitly close the connection at the end of MySQL operations. In PHP, both the die() or the exit() function outputs a message and terminates the current script. Since they can work with an OR operator, they can be incorporated to the mysqli_connect() function or the mysqli() constructor to shorten the length of PHP code. The following is the procedural version that uses the die() function. $conn = mysqli_connect('localhost', 'tcm159', 'sgky4651', 'Customers') or die("unable to connect to MySQL!"); mysqli_close($conn); The following is the object-oriented version that uses the exit() function. $conn = new mysqli('localhost', 'tcm159', 'sgky4651', 'Customers') or exit($conn->connect_error); $conn->close(); Accessing a specific database While the dbase option of the mysqli_connect() function (and the mysqli() constructor) specifies the default database to be used when performing queries, the mysqli_select_db() function is used to change the default database for the connection. In the following, the select_db() method of the mysqli class attempts to change the working database from Customers to Client. By the way, this lecture comes with three sample MySQL databases: Customers, Clients, and Endusers $conn = new mysqli('localhost', 'tcm159', 'SGkY4651', 'Customers');... $mysqli->select_db("client"); // change to Client database... The following is the procedural version. $conn = mysqli_connect('localhost', 'tcm159', 'SGkY4651', 'Customers');... mysqli_select_db($conn, "Clients");... Similar to the mysqli_connect() function, programmers might need to manually specify what to do when the mysqli_select_db() function cannot access (or the user does have the privilege to access) the Client database. if (!$conn) die(mysqli_connect_errno(). ': '. mysqli_connect_error()); It is necessary to note that programmers use select_db() only when they need to deal with two or more databases. PHP Penn Wu, PhD 328

7 The following is a complete sample code. $conn = new mysqli('localhost', 'tcm159', 'sgky4651', 'Endusers'); if ($conn->connect_error) die($conn->connect_errno. ': '. $conn->connect_error); mysqli_select_db($conn, "Clients"); if ($conn->connect_error) die($conn->connect_errno. ': '. $conn->connect_error); $sql = "SELECT * FROM ContactPerson"; $result = $conn->query($sql); if ($result) echo "Return ". $result->num_rows. " record(s)"; $result->close(); // free the result data set echo "No record returned."; $conn->close(); Running SQL statements Once a connection to the demanded database is made and maintained, programmers can call the query() method of the mysqli class or the mysqli_query() function to perform a SQL query on the database. Both query() method and mysqli_query() function are Boolean type. They return TRUE on success. The following demonstrates how to run a SQL statement, SELECT * FROM Tickets, using the query() method. The instructor chooses to store the entire SQL statement to a variable $sql, and then store the result of query execution to another variable $result. By the way, the following script attempts to access the Endusers database. $conn = new mysqli('localhost', 'tcm159', 'sgky4651', 'Endusers'); if ($conn->connect_error) die($conn->connect_errno. ': '. $conn->connect_error); $sql = "SELECT * FROM Tickets"; $result = $conn->query($sql); if ($result) PHP Penn Wu, PhD 329

8 echo "Return ". $result->num_rows. " record(s)"; $result->close(); // free the result data set echo "No record returned."; $conn->close(); A sample output is: Return 15 record(s) The following is the procedural version. The mysqli_num_rows() function returns the number of rows in a result set. The mysqli_free_result() function frees the memory associated with the result. It is necessary to note that the mysqli_query(conn, sql) function requires two parameters, in which conn specifies the MySQL connection to use and sql specifies the SQL statement. $conn = mysqli_connect('localhost', 'tcm159', 'sgky4651', 'Endusers'); if (!$conn) die(mysqli_connect_errno(). ': '. mysqli_connect_error()); $sql = "SELECT * FROM Tickets"; $result = mysqli_query($conn, $sql); if ($result) echo "Return ". mysqli_num_rows($result). " record(s)"; mysqli_free_result($result); // free the result data set mysqli_close($conn); An SQL query is based on a well-written SQL statement using SQL commands like SELECT, INSERT, UPDATE, and DELETE. Fetching data In computer technology, the term fetch means to get, read, or move data. According to the PHP document, there are several fetching functions provided by mysqli. The following list four commonly used ones. Method Function Description fetch_row() mysqli_fetch_row() Fetches one row from a result-set and returns it as an enumerated array. PHP Penn Wu, PhD 330

9 fetch_assoc() mysqli_fetch_assoc() fetch_array() mysqli_fetch_array() Fetches a result row as an associative array. Fetches a result row as an associative array, a numeric array, or both. fetch_all() mysqli_fetch_all() Fetches all result rows and returns the result-set as an associative array, a numeric array, or both. The following is a sample table (excerpted from the Customers database) that has three rows of data and one row of headings. Each row has four columns. Each column is identified by its headings: CIS, CompanyName, ContactPerson, and PhoneNumber. When a row (such as Row 0 ) is retrieved by the fetch_row() function or fetch_row() method of the mysqli class, values of four columns are stored in a temporary array. PHP programmers typically assign a variable, such as $row, to represent the temporary array in order to identify the value of each column using the $arrayname[index] format. When the Row 0 is retrieve, then $row[0] represent the value of A1012, $row[1] is MatLab Inc.. When the Row 1 is retrieve, then $row[0] represent the value of A1025, $row[1] is MathWorks Corp.. $row[0] $row[1] $row[2] $row[3] CID CompanyName ContactPerson PhoneNumber Row 0 A1012 MatLab Inc. Helen Carnegie Row 1 A1025 MathWorks Corp. Betty Simens Row 2 A1039 SouthDame Co. Anna Ariel It is necessary to note that the mysqli_fetch_row() function fetches one row from a result-set, on a row-by-row basis. PHP programmers needs to repeatedly retrieve the records row by row. A typical way to do so is to use a while loop. while ($row=mysqli_fetch_row($result)) echo "$row[0], $row[1], $row[2], $row[3] <br>"; A sample output of the above code is: A1012, MatLab Inc., Helen Carnegie, A1025, MathWorks Corp., Betty Simens, A1039, SouthDame Co., Anna Ariel, The following is the complete code. The instructor chooses to use the mysqli_error() function to display any error that happens during the mysqli_query() execution. Again, the mysqli_error() function returns the last error description for the most recent function call. $conn = mysqli_connect('localhost', 'tcm159', 'sgky4651', 'Customers'); if (!$conn) die(mysqli_connect_errno(). ': '. mysqli_connect_error()); $sql = "SELECT * FROM Company"; $result = mysqli_query($conn, $sql); if ($result) PHP Penn Wu, PhD 331

10 while ($row=mysqli_fetch_row($result)) echo "$row[0], $row[1], $row[2], $row[3]<br>"; mysqli_free_result($result); // free the result data set die(mysqli_error($conn)); mysqli_close($conn); Most tables in a MySQL database have field names. A field name is the heading of the column. In the above sample table, CID, CompanyName, ContactPerson, and PhoneNumber are the field names of the column they reside. When retrieving a row of data from a table, the automatically forms an associative array similar to the following row0 = array("cid"=>"a1012", "CompanyName"=>"MatLab Inc.", "ContactPerson"=>"Helen Carnegie", "PhoneNumber"=>" "); When a row contains many fields, it might be a convenient way to use a for loop to iterate through the $row array (instead of manually access them one by one using $row[0], $row[1],, $row[n]). The following is a sample code. The count() function is a PHP built-in function that returns the size (total number of elements) of an array. while ($row=mysqli_fetch_row($result)) for ($i=0; $i<count($row); $i++) echo $row[$i]. ", "; By definition, the mysqli_fetch_assoc() function returns an associative array that corresponds to the fetched row or NULL if there are no more rows. With this function, every filed name of a table becomes the key to retrieve the associated data; therefore, programmers can use the $row[key] format to identify every column (assuming $row is the variable that stored the return data from MySQL server). The following script also demonstrates how to incorporate an HTML table to the output of query. The data will be displayed in an HTML table. if ($result) echo "<table border=1>"; while ($row = mysqli_fetch_assoc($result)) echo "<tr><td>". $row['cid']. "</td><td>". $row['companyname']. "</td><td>". $row['contactperson']. "</td></tr>"; echo "</table>"; mysqli_free_result($result); // free the result data set PHP Penn Wu, PhD 332

11 A sample output looks: The foreach loop is an ideal repetition structure to iterate through an associative array. The following demonstrates how to use a foreach loop to iterate through the $row array. It is necessary to note that the instructor creates two arrays: $k and $v. When retrieving a row of record, $k is the variable that temporarily stores all the keys, while $v stores all the data. while ($row = mysqli_fetch_assoc($result)) echo "<tr>"; foreach ($row as $k=>$v) echo "<td>". $v. "</td>"; echo "</tr>"; The above example use both $k and $v to store keys and values. The following is another way which use the $row[$k] format. echo "<td>". $row[$k]. "</td>"; In a sense, the use of $k is redundant because the following works well and produce exactly the same result. while ($row = mysqli_fetch_assoc($result)) echo "<tr>"; foreach ($row as $v) echo "<td>". $v. "</td>"; echo "</tr>"; The mysqli_fetch_array() function is an extended version of the mysqli_fetch_row() and the mysqli_fetch_assoc() function. In addition to storing the data in the numeric indices of the result array, the mysqli_fetch_array() function can also store the data in associative indexes, using the field names of the result set as keys. In the following example, the instructor demonstrates how to use the mysqli_fetch_array() function by purposely mixed the uses of indexes and keys. if ($result) echo "<table border=1>"; while ($row = mysqli_fetch_array($result)) PHP Penn Wu, PhD 333

12 echo "<tr><td>". $row['cid']. "</td><td>". $row[1]. "</td><td>". $row['contactperson']. "</td><td>". $row[3]. "</td></tr>"; echo "</table>"; mysqli_free_result($result); // free the result data set The mysqli_fetch_all() function returns all the rows as an array in a single step, it may consume more memory than some similar functions such as mysqli_fetch_array(), which only returns one row at a time from the result set. Further, if you need to iterate over the result set, you will need a looping construct that will further impact performance. For these reasons mysqli_fetch_all() should only be used in those situations where the fetched result set will be sent to another layer for processing. if ($result) echo "<table border=1>"; $arr = mysqli_fetch_all($result, MYSQLI_ASSOC); print_r($arr); mysqli_free_result($result); // free the result data set The mysqli_fetch_row(), mysqli_fetch_assoc(), and mysqli_fetch_array() functions perform a cyclic data retrieving which means they only retrieves a row of record at a given time. It takes cycling operations to complete the data retrieving process; therefore, they need a repetition structure such as the while loop to iterate through the retrieving cycles. The mysqli_fetch_all() function retrieve every row of data from the MySQL server with only one single data retrieving operation. There is no need to use any repetition structure during the data retrieving. However, after the data are fetched. It takes a few more steps to re-organized the data. The instructor simply does not recommend to use the mysqli_fetch_all() function in this lecture. The mysqli_fetch_field() function is not a function for retrieving data. Instead, it returns information of all the fields (columns) in the result set, as an object. The object has many properties. The following lists the most commonly used properties. name - name of the column table - name of table db - database (new in PHP 5.3.6) type - data type used for the field The following demonstrates how to use the mysqli_fetch_field() function to obtain only the field names. while ($col=mysqli_fetch_field($result)) echo $col->name. ", "; A sample output looks: CID, CompanyName, ContactPerson, PhoneNumber PHP Penn Wu, PhD 334

13 The following is a complete code that demonstrates how to use the mysqli_fetch_field() function to obtains field name, and then use the mysqli_fetch_row() function to obtain all records. The retrieved data are organized in an HTML table. $conn = mysqli_connect('localhost', 'tcm159', 'sgky4651', 'Customers'); if (!$conn) die(mysqli_connect_errno(). ': '. mysqli_connect_error()); $sql = "SELECT * FROM Company"; $result = mysqli_query($conn, $sql); echo "<table border='1' cellspacing='0' cellpadding='2'>"; echo "<caption>company</caption>"; if ($result) echo "<tr>"; while ($col=mysqli_fetch_field($result)) echo "<th>". $col->name. "</th>"; echo "</tr>"; while ($row=mysqli_fetch_row($result)) echo "<tr>"; for ($i=0; $i<count($row); $i++) echo "<td>". $row[$i]. "</td>"; echo "</tr>"; mysqli_free_result($result); // free the result data set die(mysqli_error($conn)); mysqli_close($conn); A sample output looks: PHP Penn Wu, PhD 335

14 Query that returns only one row SQL-based queries typically return data row by row; however, there will be some situation that the query will only return one row as result. For example, every person can only has one and the only one blood type (A, B, O, or AB). The following is a sample query that returns the blood type of a student with student ID, D Since blood type and student ID are in a one-to-one relationship, the following query will return only one row of record. SELECT bloodtype FROM Students WHERE sid='d '; In such as situation, in which the programmer knows for sure that the query will only return one and the only row, there is no need to use any repetition structure (such a while loop), the programmer only need to call the fetch functions to extract the only one row from the query result. The following is an example. $sql = "SELECT bloodtype FROM Students WHERE sid='d ';" $result = mysqli_query($sql); $row = mysqli_fetch_assoc($result); echo $row['bloodtype']; The following is another example that uses the mysqli_fetch_row() function. $sql = "SELECT ticketno FROM tickets WHERE ticketno='db ';"; $result = mysqli_query($conn, $sql); $row = mysqli_fetch_row($result); echo $row[0]; In a situation that there are more than one value appears more than once in a table, such as A1039 in the following table, yet the programmer only needs to get one of the same values, the programmer can use the LIMIT clause to add a constraint. In MySQL, the LIMIT clause is used in the SELECT statement to constrain the number of rows in a result set. InvoiceNo CID OrderDate S A S A S A S A S A S A S A The following is a sample SQL statement that will always return only one row. The returned row is the first record in the table that match the criteria. SELECT InvoiceNo from Orders WHERE cid='a1039' LIMIT 1; A sample output looks: InvoiceNo PHP Penn Wu, PhD 336

15 S In MySQL, the ORDER BY clause can sort data when it is used with the SELECT FROM command. The following is a sample query that sorts all the retrieved records by the ticketno fields. SELECT * FROM tickets ORDER BY ticketno; The ORDER BY clause also works with both ASC and DESC keywords to specify the sorting to be in either ascending or descending order with ascending being the default. The above query, without the use of ASC keyword, is defaulted to sort in ascending order. The following, on the other hands, specifies to sort in descending order. SELECT ticketno FROM tickets ORDER BY ticketno DESC; The following query adds the LIMIT 1 constraint to the above one; therefore, only the last ticket number is returned. SELECT ticketno FROM tickets ORDER BY ticketno DESC LIMIT 1; Database maintenance Database maintenance is a term used to describe a set of tasks that are all run with the intention to improve a database. Basic maintenance tasks include adding data, update records, delete records, etc. The following table lists some of the basic database maintenance commands and SQL statements (assuming Payments is a table). Command INSERT INTO tablename DROP TABLE tablename UPDATE tablename SET DELETE FROM tablename Example INSERT INTO Payments VALUES ('A1012', 'CreditCard', 'Net15'); DROP TABLE Payments; UPDATE Payments SET option2='net10' WHERE cid='a1012'; DELETE FROM Payments WHERE cid='a1012'; The following is a complete object-oriented code that demonstrates how to add a new record, using the INSERT INTO command, to an existing table named tickets. It is necessary to note that the instructor uses a special expression, or die("error"), to handle the error. If the SQL statement runs into an error, the die() function will immediately halt the PHP script and display an text Error. $conn = new mysqli('localhost', 'tcm159', 'sgky4651', 'Endusers'); if ($conn->connect_error) die("connection failed."); $sql = "INSERT INTO tickets VALUES ('DB ', 'Sue', 'Yuan', 'syuan@yahoo.com', 0);"; $result = $conn->query($sql) or die("error"); $conn->close(); The following is another object-oriented code that demonstrates how to update a record. PHP Penn Wu, PhD 337

16 $conn = new mysqli('localhost', 'tcm159', 'sgky4651', 'Endusers'); if ($conn->connect_error) die("connection failed."); $sql = "UPDATE tickets SET lastname='yen' WHERE TicketNo='DB ';"; $result = $conn->query($sql) or die("error"); $conn->close(); The following is a procedural code that demonstrates how to delete a record from an existing table. $conn = mysqli_connect('localhost', 'tcm159', 'sgky4651', 'Endusers'); if (!$conn) die("connection failed."); $sql = "delete from tickets where ticketno='db ';"; $result = mysqli_query($conn, $sql) or die("error"); mysqli_close($conn); Interestingly, in MySQL, when using UPDATE or DELTE FROM command to update or delete a non-existing record, such as the following example, the MySQL server only show a status message 0 rows affected without returning any error message. This is because the SQL statement is valid (even when it will not return anything) and the query execution succeeds (a query can return nothing as result). In such situation, the die("error") function will not take effect because there is no error can be detected. MariaDB [Endusers]> DELETE FROM tickets where ticketno = 'DB '; Query OK, 0 rows affected (0.00 sec) One way to handle such situation is to run multiple queries: the first query checks if the demanded record actually exists; the second query either update or delete the record after the first query confirms the existence of the record. The following is an example. $sql = "SELECT ticketno FROM tickets WHERE ticketno='". $ticketno. "';"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) mysqli_free_result($result); $sql = "DELETE FROM tickets WHERE ticketno='". $ticketno. "';"; $result = mysqli_query($conn, $sql) or die("error"); echo "<p>$ticketno ticket deleted successfully.</p>"; PHP Penn Wu, PhD 338

17 echo "<p>no matching $ticketno ticket.</p>"; SQL queries that retrieve data from two or more tables This lecture comes with three sample database: Customers, Clients, and Endusers. Each database contain two or more tables. Between every two tables, there is at least one filed that appears in both table as the foreign key to each other. They foreign key allows these two tables to build a relationship. Through the relationship, data can be retrieved from both table as long as long their foreign keys have exactly the same value. The following figure illustrates the relationship among the three tables of the Customers database. PaymentMethod CID (pk, fk) Option1 Option2 Company CID (pk, fk) CompanyName ContactPerson PhoneNumber MailingAddress City State LastContactedDate Orders InoviceNo (pk) CID (fk) OrderDate ShipDate Total UnpaidBalance LastPaymentDate All the three tables contains a field named CID ; therefore, a well-formed SQL statement can retrieve data from the Company table, then retrieve data from the Orders table as long as the SQL query can find a record with exactly the same value of CID. In the following figure, both Company and Orders contains records with CID equals to A1039. Company A1039 SouthDame Co. Anna Ariel Main St. West Hills CA Orders S A The following is a sample SQL statement that can retrieves data from both Company and Orders table. It is necessary to note that, when there are more than one table in an SQL statement, be sure to use the tablename.fieldname format to clearly specify which table to work on. Both Company and Orders table contain the CID field; therefore, the field name alone cid is not sufficient to specify which table the cid field should the query execution work on. Yet, company.cid and orders.cid clearly specify cid field of the company table and cid field of the orders table. By the way, MySQL suggests to use single quotes to enclose text values, such as 'a1039'. SELECT * FROM Company, orders WHERE company.cid='a1039' AND company.cid=orders.cid; On the other hand, it is necessary to specify all the table names in the SELECT FROM clause. Use the comma (,) as delimiter (or separator) between every two table names, as shown below....from Company, orders... In SQL, the WHERE clause is used to extract only those records that fulfill a specified criterion. The term criteria means one or more conditions that must be met before records are retrieved. In PHP Penn Wu, PhD 339

18 the following WHERE clause, the criteria uses an AND operator. In SQL, the AND operator displays a record if both the first condition and the second condition are true. With the following criteria, the MySQL server will first go to the Company table to find whether or not a record with cid= 'a1039' exists. If so, then it will go to the "Orders" table to find any record(s) that also meet cid='a1039'. Eventually, all matched records from both table will be retrieved for further processing. WHERE company.cid='a1039' AND company.cid=orders.cid The following illustrates how the instructor assigns the SQL statement as value to the $sql variable, and later execute the SQL statement with the function.... $sql = "SELECT * FROM Company, orders WHERE company.cid='a1039' AND company.cid=orders.cid;"; $result = mysqli_query($conn, $sql);... The following figure illustrates that all the three tables of the Customers database contain at least one value of CID that is a1039. PaymentMethod.. A1039. Company.. A1039. Orders.. A1039. The following is a sample query that can retrieve records from these three tables. It is necessary to note that there must be a mechanism in the WHERE clause to specify that CID field of the three table must have exactly the same value; therefore, the instructor chooses to use two AND operators. The logic is A equals B, and B equals C, then A also equals C. SELECT * FROM Company, orders, paymentmethod WHERE company.cid='a1039' AND company.cid=orders.cid AND company.cid=paymentmethod.cid; Using HTML form as user interface to specify query keywords Data-driven web sites, such as Amazon.com, typically provide a textbox for users to enter a keyword in order to run a query to search for matching records. In the following sample code, the instructor adds an HTML code that can post a text (which is supposed a customer s id) to the PHP agent. The PHP agent uses the $_POST array to store all the passed value. One of the passed value has key, cid, whose value will be used in the SQL statement to run a query. It is necessary to note that the value stored in $_POST['cid'] is transferred to a variable $cid. The SQL statement is a concatenated string: "SELECT * FROM Company WHERE cid='". $cid. "';", in which the value stored in the $cid variable is inserted to the string to produce a complete SQL statement similar to : "SELECT * FROM Company WHERE cid='a1012';". if ($_POST) $cid = $_POST['cid']; $conn = mysqli_connect('localhost', 'tcm159', 'sgky4651', 'Customers'); if (!$conn) die(mysqli_connect_errno(). ': '. mysqli_connect_error()); PHP Penn Wu, PhD 340

19 $sql = "SELECT * FROM Company WHERE cid='". $cid. "';"; $result = mysqli_query($conn, $sql); if ($result) while ($row=mysqli_fetch_row($result)) for ($i=0; $i<count($row); $i++) echo $row[$i]. ", "; echo "<br>"; mysqli_free_result($result); // free the result data set die("no record found with <b>'". $cid. "'</b>."); mysqli_close($conn); <form action=" echo $_SERVER['PHP_SELF'];" method="post"> Customer ID: <input type="text" name="cid"> <input type="submit" value="submit"> </form> A sample output looks: and As illustrates in the above figure, when the user enters a valid keyword, the SQL statement will execute and bring the query result to the PHP agent for further formatting with HTML code. Only the formatted HTML code will be returned to the client browser. Review Questions 1. Given the following code segment, which statement is correct? $conn = mysqli_connect("localhost","joeuser","34nhjp") or die(mysqli_error()); A. The die() function would execute only if the connection failed. B. The mysqli_error() function prints an error message when connect to the database. C. The database name is localhost, your username is 34Nhjp, and your password is joeuser. D. The mysqli_connect() function selects a database on the MySQL server. PHP Penn Wu, PhD 341

20 2. Given the following code segment, which statement is correct? $db = mysqli_select_db("mydb", $conn); A. It selects a MySQL database called MyDB. B. It selects a table called MyDB. C. It selects a column called MyDB. D. It selects a record called MyDB. 3. Given the following code segment, which statement is correct? $result = mysqli_query($conn, $sql); A. $result formats the results held by the mysqli_query() function. B. $result is a variable to hold the result of the query, carried out by the mysqli_query() function. C. $result is built-in function that access the data delivered by mysqli_query() function. D. $result is built-in function that carries out the query held by mysqli_query() function. 4. Given the following PHP code segment, which is the part that builds a connection to MySQL server named "cis246" using the "admin" account with password "solo123" to access the "Clients" database? A. $conn = mysqli_select_db("cis246","admin","solo123","clients"); B. $conn = mysqli_connect("cis246","admin","solo123","clients"); C. $conn = mysqli_query("cis246","admin","solo123","clients"); D. $conn = mysqli_db_connection("cis246","admin","solo123","clients"); 5. Given the following code segment, which can display the data type used for the field in the table? $sql = "SELECT * FROM Company";... $result = mysql_query("select * FROM student"); while ($col=mysqli_fetch_field($result)) A. echo gettype($col); B. echo $col['type']; C. echo $col->type; D. echo $col('type'); 6. Given the following table and a query handled by the mysqli_fetch_assoc() function in a while loop, which can list all the ISBN numbers one by one? Assuming $row is in use. A. $k=0; echo $row[$k]; B. $k="isbn"; echo $row[$k[0]]; C. echo $row[0]; D. echo $row['isbn']; ISBN Author Publisher Lucy Chen Apex Inc Helen Smith Braun Publishing Corp Terrie Garcia Oxmoore House 7. Given the following table, a PHP developer chooses the mysqli_fetch_field() function to retrieve data from it. Which is possibly the result? ISBN Author Publisher PHP Penn Wu, PhD 342

21 Lucy Chen Apex Inc Helen Smith Braun Publishing Corp Terrie Garcia Oxmoore House A , , B. Lucy Chen, Helen Smith, Terrie Garcia C. Apex Inc., Braun Publishing Corp., Oxmoore House D. ISBN, Author, Publisher 8. Given the following table, a PHP developer chooses the mysqli_fetch_row() function to retrieve data from it. Which is possibly the result? ISBN Author Publisher Lucy Chen Apex Inc Helen Smith Braun Publishing Corp Terrie Garcia Oxmoore House A. ISBN, Author, Publisher B , Lucy Chen, Apex Inc. C. 3 D. Author, Lucy Chen, Helen Smith, Terrie Garcia 9. Given the following code segment,. $result = mysqli_query("select * FROM student"); while ( $row = mysqli_fetch_array($result) ) echo$row["firstname"]); A. "student" is the name of the database. B. $row is a PHP keyword that indicates a row in the result set. C. $row["firstname"] represent the value of the firstname filed of a row of record. D. the while loop will stop when $row["firstname"] equals "student". 10. Assuming that the "DB " data exists in the "ticketno" field of the "tickets" table. Which can display the value of the "issue_date" field? $sql = "SELECT ticketno, issue_date, price FROM tickets WHERE ticketno = 'DB ';"; $result = mysqli_query($conn, $sql); $row = mysqli_fetch_row($result); A. echo $row[0]; B. echo $row['issue_date']; C. echo $row[1]; D. echo $row["issue_date"]; PHP Penn Wu, PhD 343

22 Lab #12 PHP and MySQL Preparation #1: Running the server and create default database 1. Plug in the USB flash drive and record the drive name:. [Note: Each time when plugging the USB flash drive, the system might assign a different drive name. Do not assume any default.] 2. Close all the applications that may cause conflicts with XAMPP such as Skype, IIS, Wampserver, VMware, etc. 3. Use Windows Explorer to find the X:\xampp\setup_xampp.bat file (where X is the drive name such as F ), and the double click it to launch the program. One of the following messages will be displayed in the popped-up Command Prompt. Situation 1 Situation 2 Sorry, but... nothing to do! Do you want to refresh the XAMPP installation? 1) Refresh now! Press any key to continue... x) Exit 4. If encountering the Situation 2, simply press 1 and press [Enter] to refresh (reconfiguring) settings to match with the new drive name (if necessary). After the re-configuration succeeds, the following message will appear. XAMPP is refreshing now... Refreshing all paths in config files... Configure XAMPP with awk for Windows_NT ###### Have fun with ApacheFriends XAMPP! ###### Press any key to continue Press any key to close the command prompt. 6. Double click the X:\xampp\xampp-control.exe file (replace X with the drive name) to launch the XAMPP Control Panel, and then start Apache. 7. Click the Start button next to MySQL to launch the MySQL server. Refer to Appendix A of Lecture #1 if you receive the Port 3306 in use error. 8. Open a Command Prompt. 9. In the prompt, type x: and press Enter, where x is the drive name of the USB drive. The following use E as example. C:\Users\user>e: E:\> 10. Type notepad sql.bat and press [Enter] to use Notepad to create new batch file named sql.bat. Click Yes to confirm. PHP Penn Wu, PhD 344

23 @echo off path=%path%;%cd%xampp\mysql\bin; mysql -u root -p 11. Save and exit the sql.bat file. 12. Type sql.bat and press [Enter] to runt the sql.bat file. E:\>sql.bat 13. When being prompted to enter the password, simply press [Enter]. The MariaDB [(none)]> prompt should now appear. Enter password: Welcome to the MariaDB monitor. Command end with ; or \g. Your MariaDB connection id is 2 Server version: MariaDB mariadb.org binary distribution... MariaDB [(none)]> 14. Type SHOW DATABASES; and press [Enter] to display a list of the currently available databases. A sample output looks: MariaDB [(none)]> SHOW DATABASES; Database information_schema mysql performance_schema phpmyadmin test rows in set (0.00 sec) 15. Type exit and press [Enter] to exit MySQL. MariaDB [(none)]> exit Bye 16. Close the Command Prompt. Preparation #2: Create MySQL databases and users 1. Download the sqlstatement.zip file, and then extract the data1.sql file to the root directory of the drive. Make sure the path is x:\data1.sql, where x is the drive name. 2. Open a Command Prompt. 3. Type x: and press [Enter] to change to the X: drive, where x is the drive name of the USB flash drive. The following use e as example. C:\Users>user>e: 4. Type sql.bat and press [Enter] to launch MySQL. Press [Enter] to bypass the password inquiry. PHP Penn Wu, PhD 345

24 E:\>sql.bat 5. Type SOURCE x:\data1.sql and press [Enter], where x is the drive name, to continuously execute all of the above SQL statements. MariaDB [customers]> SOURCE e:\data1.sql Query OK, 1 row affected (19.29 sec)... Query OK, 1 row affected (20.01 sec) 6. Type SHOW DATABASES; and press [Enter] to display a list of the currently available databases. Verify that the Customers, Clients, and Enduers databases are in the list. MariaDB [(none)]> SHOW DATABASES; Database clients customers endusers... phpmyadmin test rows in set (0.00 sec) 7. Type use customers; and press [Enter] to manually select the Customers database. MariaDB> user customers; Database changed 8. Type show tables; and press [Enter] to display all available tables of the Customer database. MariaDB> show tables; Tables_in_customers company orders paymentmethod rows in set (0.01 sec) 9. Type select * from company; and press [Enter] to display the entire company table. MariaDB> select * from company; CID CompanyName ContactPerson PhoneNumber MailingAddress City State LastContactedDate A1012 MatLab Inc. Helen Carnegie Via San Pedro St. Long Beach CA A1025 MathWorks Corp. Betty Simens Anderson Blvd. Pomona CA A1039 SouthDame Co. Anna Ariel Main St. West Hills CA A1043 Eastern Technology Jenny Ngo Kimberly Court Cypress CA A1056 Aspen Sciences. Erica Strickland Hackbart Rd. Irvine CA A1064 Harazawa Foods. Mariko Yamada Central Ave. Long Beach CA PHP Penn Wu, PhD 346

25 A1078 Tong Hai Precisions. Linda Zhao Wiley Dr. Diamond Bar CA A1081 Worcester Institute Stacy Barger Glory St. Chino Hills CA A1097 Texas Watches Lucy Park Spectrum Parkway Irvine CA rows in set (0.00 sec) Learning Activity #1: 1. In the X:\xampp\htdocs\myphp directory (create the myphp subdirectory if it does not exist), use Notepad to create a new file named lab12_1.php with the following contents: $conn = mysqli_connect('localhost', 'tcm159', 'sgky4651', 'Customers'); if (!$conn) die(mysqli_connect_errno(). ': '. mysqli_connect_error()); $sql = "SELECT * FROM Company"; $result = mysqli_query($conn, $sql); if ($result) echo "<table border=1>"; while ($col=mysqli_fetch_field($result)) echo "<th>". $col->name. "</th>"; echo "</tr>"; while ($row = mysqli_fetch_row($result)) echo "<tr>"; for ($i=0; $i<count($row); $i++) echo "<td>". $row[$i]. "</td>"; echo "</tr>"; echo "</table>"; mysqli_free_result($result); // free the result data set die(mysqli_error($conn)); mysqli_close($conn); 2. Test the program. A sample output looks like: PHP Penn Wu, PhD 347

26 3. Download the assignment template, and rename it to lab12.doc if necessary. Capture a screen shot similar to the above figure and paste it to a Word document named lab12.doc (or lab12.docx). Learning Activity #2: Query across tables 1. In the X:\xampp\htdocs\myphp directory (create the myphp subdirectory if it does not exist), use Notepad to create a new file named lab12_2.php with the following contents: <!Doctype html> <html> <body> if ($_POST) $cid = $_POST['cid']; $conn = mysqli_connect('localhost', 'tcm159', 'sgky4651', 'Customers'); if (!$conn) die(mysqli_connect_errno(). ': '. mysqli_connect_error()); $sql = "SELECT * FROM Company, orders, paymentmethod WHERE company.cid='". $cid. "' AND company.cid=orders.cid AND company.cid=paymentmethod.cid;"; $result = mysqli_query($conn, $sql); if ($result) while ($row=mysqli_fetch_assoc($result)) echo "<p>customer ID: <b>". $row['cid']. "</b><br>"; echo "Company Name: <b>". $row['companyname']. "</b><br>"; echo "Contact Person: <b>". $row['contactperson']. "</b><br>"; echo "Phone Number: <b>". $row['phonenumber']. "</b><br>"; echo "Address: <b>". $row['mailingaddress']. ", ". $row['city']. ", ". $row['state']. "</b><br>"; echo "Last Contacted Date: <b>". $row['lastcontacteddate']. "</b><br>"; echo "Invoice Number: <b>". $row['invoiceno']. "</b><br>"; echo "Order Date: <b>". $row['orderdate']. "</b><br>"; echo "Shipment Date: <b>". $row['shipdate']. "</b><br>"; echo "Total: <b>". $row['total']. "</b><br>"; echo "Unpaid Balance: <b>". $row['unpaidbalance']. "</b><br>"; echo "Last Payment Date: <b>". $row['lastpaymentdate']. "</b><br>"; echo "Payment Option 1: <b>". $row['option1']. "</b><br>"; echo "Payment Option 2: <b>". $row['option2']. "</b></p>"; mysqli_free_result($result); // free the result data set PHP Penn Wu, PhD 348

27 die("no record found with <b>'". $cid. "'</b>."); mysqli_close($conn); <form action=" echo $_SERVER['PHP_SELF'];" method="post"> Customer ID: <input type="text" name="cid"><br> <input type="submit" value="submit"> </form> </body> </html> 2. Test the program. A sample output looks like: 3. Capture a screen shot similar to the above figure and paste it to a Word document named lab12.doc (or lab12.docx). Learning Activity #3: Query across databases 1. In the X:\xampp\htdocs\myphp directory (create the myphp subdirectory if it does not exist), use Notepad to create a new file named lab12_3.php with the following contents: <!Doctype html> <html> <body> if ($_POST) $cid = $_POST['cid']; $conn = mysqli_connect('localhost', 'tcm159', 'sgky4651', 'Customers'); if (!$conn) die(mysqli_connect_errno(). ': '. mysqli_connect_error()); and PHP Penn Wu, PhD 349

28 /////// query 1 ///////// $sql = "SELECT * FROM Company WHERE cid='". $cid. "';"; $result = mysqli_query($conn, $sql); if ($result) echo "Database: Customer<br>"; while ($row=mysqli_fetch_assoc($result)) echo "<p>customer ID: <b>". $row['cid']. "</b><br>"; echo "Company Name: <b>". $row['companyname']. "</b><br>"; echo "Contact Person: <b>". $row['contactperson']. "</b><br>"; echo "Phone Number: <b>". $row['phonenumber']. "</b><br>"; echo "Address: <b>". $row['mailingaddress']. ", ". $row['city']. ", ". $row['state']. "</b><br>"; echo "Last Contacted Date: <b>". $row['lastcontacteddate']. "</b><p>"; mysqli_free_result($result); // free the result data set die("no record found with <b>'". $cid. "'</b>."); /////// query 2 ///////// mysqli_select_db($conn, "Clients"); if (!$conn) die("connecting to 'Clients' database failed."); $sql = "SELECT pid from ContactPerson WHERE cid='". $cid. "' LIMIT 1;"; $result= mysqli_query($conn, $sql); $row = mysqli_fetch_row($result); $pid = $row[0]; $sql = "SELECT * FROM ContactPerson, CreditRating WHERE ContactPerson.pid='". $pid. "' AND ContactPerson.PID=CreditRating.PID;"; $result = mysqli_query($conn, $sql); if ($result) echo "Database: Client<br>"; echo "<table border='1' cellspacing='0' cellpadding='2'>"; echo "<caption>$pid</caption><tr>"; ////// field name ////// while ($col=mysqli_fetch_field($result)) if ($col->name!= "PID") echo "<th>". $col->name. "</th>"; echo "</tr>"; PHP Penn Wu, PhD 350

29 ///// field data //////// while ($row=mysqli_fetch_assoc($result)) foreach ($row as $k=>$v) if ($k!= "PID") echo "<td>". $v. "</td>"; echo "</tr>"; echo "</table>"; mysqli_free_result($result); // free the result data set die("no record found with <b>'". $cid. "'</b>."); mysqli_close($conn); <form action=" echo $_SERVER['PHP_SELF'];" method="post"> Customer ID: <input type="text" name="cid"><br> <input type="submit" value="submit"> </form> </body> </html> 2. Test the program. A sample output looks like: 3. Capture a screen shot similar to the above figure and paste it to a Word document named lab12.doc (or lab12.docx). and Learning Activity #4: Sample Data-entry interface 1. In the X:\xampp\htdocs\myphp directory (create the myphp subdirectory if it does not exist), use Notepad to create a new file named lab12_4.php with the following contents: <!Doctype html> <html> <body> <table border='0'> PHP Penn Wu, PhD 351

30 <form name="form1" action=" echo $_SERVER['PHP_SELF'];" method="post"> <tr><td align='right'>first Name: </td><td><input type="text" name="fname"></td></tr> <tr><td align='right'>last Name: </td><td><input type="text" name="lname"></td></tr> <tr><td align='right'> </td><td><input type="text" name=" "></td></tr> <tr><td align='right'>ticket Number: </td><td><input type="text" name="ticketno"> (for existing ticket only)</td></tr> <tr><td></td><td> <input type="hidden" name="action"> <input type="submit" value="insert" onclick="form1.action.value='insert'"> <input type="submit" value="update" onclick="form1.action.value='update'"> <input type="submit" value="delete" onclick="form1.action.value='delete'"> </td></tr> </form> </table> if ($_POST) $action = $_POST['action']; $fname = $_POST['fname']; $lname = $_POST['lname']; $ = $_POST[' ']; $ticketno = $_POST['ticketno']; switch (strtolower($action)) case "insert": insertdata($fname, $lname, $ ); break; case "update": updatedata($fname, $lname, $ , $ticketno); break; case "delete": deletedata($ticketno); break; $_POST=NULL; //////// function for insert ///////// function insertdata($fname, $lname, $ ) $conn = mysqli_connect('localhost', 'tcm159', 'sgky4651', 'Endusers'); if (!$conn) die("cannot access the database."); $sql = "SELECT ticketno FROM tickets ORDER BY ticketno DESC LIMIT 1;"; $result = mysqli_query($conn, $sql) or die("error"); if ($result) $row = mysqli_fetch_row($result); $row = explode('-', $row[0]); // split the string to array $prefix = $row[0]; // assign 'DB16' to prefix $lastticketno = $row[1]; // assign to lastticketno PHP Penn Wu, PhD 352

31 $lastticketno++; // increment by 1 $newticketno = $prefix. "-". $lastticketno; mysqli_free_result($result); die("no existing ticket number."); /////////// insert data //////////// $sql = "INSERT INTO tickets VALUES ('". $newticketno."', '". $fname. "', '". $lname. "', '". $ . "', 0);"; $result = mysqli_query($conn, $sql) or die("error"); if ($result) echo "<p>the following data inserted successfully.<ul>"; echo "<li>ticket Number: $newticketno</li>"; echo "<li>first name: $fname</li>"; echo "<li>last name: $lname</li>"; echo "<li> $ </li>"; echo "<li>flag: 0</ul></p>"; die("data inserting failed."); mysqli_close($conn); ///////// function for update /////////// function updatedata($fname, $lname, $ , $ticketno) $conn = mysqli_connect('localhost', 'tcm159', 'sgky4651', 'Endusers'); if (!$conn) die("cannot access the database."); $sql = "SELECT ticketno FROM tickets WHERE ticketno LIKE '". $ticketno. "';"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) mysqli_free_result($result); $sql = "UPDATE Tickets SET firstname='". $fname. "', lastname='". $lname. "', ='". $ . "' WHERE ticketno='". $ticketno. "';"; $result = mysqli_query($conn, $sql) or die("error"); echo "<p>information of $ticketno has been updated to:<ul>"; echo "<li>first name: $fname</li>"; echo "<li>last name: $lname</li>"; echo "<li> $ </ul></p>"; echo "<p>the search found no matching ticket, so a new ticket is issued.</p>"; insertdata($fname, $lname, $ ); PHP Penn Wu, PhD 353

32 mysqli_close($conn); ///////// function for delete /////////// function deletedata($ticketno) $conn = mysqli_connect('localhost', 'tcm159', 'sgky4651', 'Endusers'); if (!$conn) die("cannot access the database."); $sql = "SELECT ticketno FROM tickets WHERE ticketno='". $ticketno. "';"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) mysqli_free_result($result); $sql = "DELETE FROM tickets WHERE ticketno='". $ticketno. "';"; $result = mysqli_query($conn, $sql) or die("error"); echo "<p>$ticketno ticket deleted successfully.</p>"; echo "<p>no matching $ticketno ticket.</p>"; mysqli_close($conn); </body> </html> 2. Test the program. A sample output looks like: 3. Capture a screen shot similar to the above figure and paste it to a Word document named lab12.doc (or lab12.docx). Learning Activity #5: Building an SQL-Statement Testbed 1. In the X:\xampp\htdocs\myphp directory (create the myphp subdirectory if it does not exist), use Notepad to create a new file named lab12_5.php with the following contents: <!Doctype html> <html> PHP Penn Wu, PhD 354

33 <body> <form action=" echo $_SERVER['PHP_SELF'];" method="post"> <p>user ID: <input type="text" name="uid"><br> Password: <input type="password" name="psd"></p> <p>database name: <input type="text" name="dname"></p> SQL Statement: <br><textarea rows='10' cols='70' name="sql"></textarea> <input type="submit" value="submit"> </form> if ($_POST) $uid = $_POST['uid']; $psd = $_POST['psd']; $dname = $_POST['dname']; $sql = $_POST['sql']; $conn = mysqli_connect('localhost', $uid, $psd, $dname); if (!$conn) die("connection failed."); $result = mysqli_query($conn, $sql); $n = mysqli_num_rows($result); if ($result) if ($n > 0) echo "<p>query result:</p>"; echo "<table border='1' cellspacing='0' cellpadding='2'>"; // get field names echo "<tr>"; while ($col=mysqli_fetch_field($result)) echo "<th>". $col->name. "</th>"; echo "</tr>"; // rows of records while ($row=mysqli_fetch_row($result)) echo "<tr>"; for ($i=0; $i<count($row); $i++) echo "<td>". $row[$i]. "</td>"; echo "</tr>"; echo "</table>"; mysqli_free_result($result); PHP Penn Wu, PhD 355

34 echo "SQL statement executed successfully."; die("sql statement failed."); mysqli_close($conn); </body> </html> 2. Test the program using the following SQL statements (with the Endusers database): No. SQL Statement 1 CREATE TABLE IF NOT EXISTS Actress ( AID varchar(5) NOT NULL, FirstName varchar(25) NOT NULL, LastName varchar(25) NOT NULL, BirthDate Date NOT NULL, PRIMARY KEY(AID) ); 2 Enter the following statement one by one: INSERT INTO Actress Value('A1023', 'Joy', 'Bryant', ' '); INSERT INTO Actress Value('A1024', 'Kim', 'Zimmer', ' '); INSERT INTO Actress Value('A1025', 'Lucy', 'Liu', ' '); INSERT INTO Actress Value('A1026', 'Jennifer', 'Lopez', ' '); 3 UPDATE Actress SET BirthDate=' ' WHERE aid='a1025'; 4 DELETE FROM Actress WHERE aid='a1025'; 3. A sample output looks like: 4. Capture a screen shot similar to the above figure and paste it to a Word document named lab12.doc (or lab12.docx). Submitting the lab 1. Create a.zip file named lab12.zip containing: Lab12_1.php Lab12_2.php Lab12_3.php Lab12_4.php Lab12_5.php Lab12.doc (or.docx, or.pdf) [You may be given zero point if this required document is missing] PHP Penn Wu, PhD 356

35 2. Upload the zipped file as response to question 11 or Assignment 12 (available in Blackboard). Programming Exercise #12 1. Use Notepad to create a new file named ex12.php with the following three lines in it (be sure to replace YourFullNameHere with the correct one): // CIS246 // File name: ex12.php // Student: YourFullNameHere 2. Next to the above lines, write PHP codes that can execute a SQL statement to retrieve records from the tickets table of the Endusers database. 3. Once the recordsets are retrieved, use both the mysqli_fetch_field() and mysqli_fetch_assoc() functions to obtain the field names and rows of records sequentially. Use a foreach loop to iterate through all the rows of records returned by the mysqli_fetch_assoc() function. 4. Use the <table>, <caption>, <tr>, <th>, and <td> tags of HTML to organize the data into an HTML table. Make sure the look similar to the following. 5. Download the programming exercise template, and rename it to ex12.doc. Capture a screen shot similar to the above figure and paste it to a Word document named ex12.doc (or ex12.docx). 6. Create a.zip file named ex12.zip with the following two files. Upload the.zip file for grading. ex12.php ex12.doc (or ex12.docx or.pdf) [You may be given zero point if this required document is missing] Grading Criteria 1. You code must fully comply with the requirement to earn full credits. No partial credit is given. Appendix A: Database Structure Database: Customers PaymentMethod CID (pk, fk) Option1 Option2 Company CID (pk, fk) CompanyName ContactPerson PhoneNumber MailingAddress City State LastContactedDate Orders InoviceNo (pk) CID (fk) OrderDate ShipDate Total UnpaidBalance LastPaymentDate PHP Penn Wu, PhD 357

Networks and Web for Health Informatics (HINF 6220) Tutorial 13 : PHP 29 Oct 2015

Networks and Web for Health Informatics (HINF 6220) Tutorial 13 : PHP 29 Oct 2015 Networks and Web for Health Informatics (HINF 6220) Tutorial 13 : PHP 29 Oct 2015 PHP Arrays o Arrays are single variables that store multiple values at the same time! o Consider having a list of values

More information

Web Programming. Dr Walid M. Aly. Lecture 10 PHP. lec10. Web Programming CS433/CS614 22:32. Dr Walid M. Aly

Web Programming. Dr Walid M. Aly. Lecture 10 PHP. lec10. Web Programming CS433/CS614 22:32. Dr Walid M. Aly Web Programming Lecture 10 PHP 1 Purpose of Server-Side Scripting database access Web page can serve as front-end to a database Ømake requests from browser, Øpassed on to Web server, Øcalls a program to

More information

2017 Politecnico di Torino 1

2017 Politecnico di Torino 1 SQL for the applications Call Level Interface Requests are sent to the DBMS through functions of the host language solution based on predefined interfaces API, Application Programming Interface SQL instructions

More information

2017 Politecnico di Torino 1

2017 Politecnico di Torino 1 SQL for the applications Call Level Interface Requests are sent to the DBMS through functions of the host language solution based on predefined interfaces API, Application Programming Interface SQL instructions

More information

The M in LAMP: MySQL CSCI 470: Web Science Keith Vertanen Copyright 2014

The M in LAMP: MySQL CSCI 470: Web Science Keith Vertanen Copyright 2014 The M in LAMP: MySQL CSCI 470: Web Science Keith Vertanen Copyright 2014 MySQL Setup, using console Data types Overview Creating users, databases and tables SQL queries INSERT, SELECT, DELETE WHERE, ORDER

More information

Web Systems Nov. 2, 2017

Web Systems Nov. 2, 2017 Web Systems Nov. 2, 2017 Topics of Discussion Using MySQL as a Calculator Command Line: Create a Database, a Table, Insert Values into Table, Query Database Using PhP API to Interact with MySQL o Check_connection.php

More information

AN INTRODUCTION TO WEB PROGRAMMING. Dr. Hossein Hakimzadeh Department of Computer and Information Sciences Indiana University South Bend, IN

AN INTRODUCTION TO WEB PROGRAMMING. Dr. Hossein Hakimzadeh Department of Computer and Information Sciences Indiana University South Bend, IN AN INTRODUCTION TO WEB PROGRAMMING Dr. Hossein Hakimzadeh Department of Computer and Information Sciences Indiana University South Bend, IN HISTORY Developed by Michael Widenius. Initially release in 1995.

More information

Chapter 7 PHP Files & MySQL Databases

Chapter 7 PHP Files & MySQL Databases Chapter 7 PHP Files & MySQL Databases At the end of the previous chapter, a simple calendar was displayed with an appointment. This demonstrated again how forms can be used to pass data from one page to

More information

Similarly, example of memory address of array and hash are: ARRAY(0x1a31d44) and HASH(0x80f6c6c) respectively.

Similarly, example of memory address of array and hash are: ARRAY(0x1a31d44) and HASH(0x80f6c6c) respectively. Lecture #9 What is reference? Perl Reference A Perl reference is a scalar value that holds the location of another value which could be scalar, arrays, hashes, or even a subroutine. In other words, a reference

More information

Web Application Development (WAD) V th Sem BBAITM (Unit 4) By: Binit Patel

Web Application Development (WAD) V th Sem BBAITM (Unit 4) By: Binit Patel Web Application Development (WAD) V th Sem BBAITM (Unit 4) By: Binit Patel Working with Forms: A very popular way to make a web site interactive is using HTML based forms by the site. Using HTML forms,

More information

Database Connectivity using PHP Some Points to Remember:

Database Connectivity using PHP Some Points to Remember: Database Connectivity using PHP Some Points to Remember: 1. PHP has a boolean datatype which can have 2 values: true or false. However, in PHP, the number 0 (zero) is also considered as equivalent to False.

More information

PHP Development - Introduction

PHP Development - Introduction PHP Development - Introduction Php Hypertext Processor PHP stands for PHP: Hypertext Preprocessor PHP is a server-side scripting language, like ASP PHP scripts are executed on the server PHP supports many

More information

Professional PHP for working with MySQL

Professional PHP for working with MySQL Chapter 19 Professional PHP for working with MySQL PDO (PHP Data Objects) Pros Is included with PHP 5.1 and later and available for 5.0. Provides an object-oriented interface. Provides a consistent interface

More information

MySQL: Access Via PHP

MySQL: Access Via PHP MySQL: Access Via PHP CISC 282 November 15, 2017 phpmyadmin: Login http://cisc282.caslab. queensu.ca/phpmyadmin/ Use your NetID and CISC 282 password to log in 2 phpmyadmin: Select DB Clicking on this

More information

Retrieving Query Results

Retrieving Query Results Using PHP with MySQL Retrieving Query Results The preceding section of this chapter demonstrates how to execute simple queries on a MySQL database. A simple query, as I m calling it, could be defined as

More information

LAMP Apps. Overview. Learning Outcomes: At the completion of the lab you should be able to:

LAMP Apps. Overview. Learning Outcomes: At the completion of the lab you should be able to: LAMP Apps Overview This lab walks you through using Linux, Apache, MySQL and PHP (LAMP) to create simple, yet very powerful PHP applications connected to a MySQL database. For developers using Windows,

More information

The Movies table PartID Title Actor Type Cost... A1027 Around the world in 80 days

The Movies table PartID Title Actor Type Cost... A1027 Around the world in 80 days Lecture #12 Concept of data-driven web sites Database With most of the services on the web being powered by web database applications, it becomes important for any web developer to know how bring together

More information

Comp 519: Web Programming Autumn 2015

Comp 519: Web Programming Autumn 2015 Comp 519: Web Programming Autumn 2015 Advanced SQL and PHP Advanced queries Querying more than one table Searching tables to find information Aliasing tables PHP functions for using query results Using

More information

Hello everyone! Page 1. Your folder should look like this. To start with Run your XAMPP app and start your Apache and MySQL.

Hello everyone! Page 1. Your folder should look like this. To start with Run your XAMPP app and start your Apache and MySQL. Hello everyone! Welcome to our PHP + MySQL (Easy to learn) E.T.L. free online course Hope you have installed your XAMPP? And you have created your forms inside the studio file in the htdocs folder using

More information

Multimedia im Netz Online Multimedia Winter semester 2015/16

Multimedia im Netz Online Multimedia Winter semester 2015/16 Multimedia im Netz Online Multimedia Winter semester 2015/16 Tutorial 05 Minor Subject Ludwig-Maximilians-Universität München Online Multimedia WS 2015/16 - Tutorial 05 (NF) - 1 Today s Agenda Discussion

More information

Development Technologies. Agenda: phpmyadmin 2/20/2016. phpmyadmin MySQLi. Before you can put your data into a table, that table should exist.

Development Technologies. Agenda: phpmyadmin 2/20/2016. phpmyadmin MySQLi. Before you can put your data into a table, that table should exist. CIT 736: Internet and Web Development Technologies Lecture 10 Dr. Lupiana, DM FCIM, Institute of Finance Management Semester 1, 2016 Agenda: phpmyadmin MySQLi phpmyadmin Before you can put your data into

More information

APLIKACJE INTERNETOWE 8 PHP WYKORZYSTANIE BAZY DANYCH MYSQL

APLIKACJE INTERNETOWE 8 PHP WYKORZYSTANIE BAZY DANYCH MYSQL APLIKACJE INTERNETOWE 8 PHP WYKORZYSTANIE BAZY DANYCH MYSQL PLAN PREZENTACJI Bazy danych w PHP Połączenie z bazą danych Zamknięcie połączenie Tworzenie bazy danych Tworzenie tabeli Operacje na tabelach

More information

What is MySQL? [Document provides the fundamental operations of PHP-MySQL connectivity]

What is MySQL? [Document provides the fundamental operations of PHP-MySQL connectivity] What is MySQL? [Document provides the fundamental operations of PHP-MySQL connectivity] MySQL is a database. A database defines a structure for storing information. In a database, there are tables. Just

More information

Getting started 7. Performing operations 25

Getting started 7. Performing operations 25 Contents Contents 1 2 3 Getting started 7 Introducing PHP & MySQL 8 Understanding the cloud 9 Installing Abyss Web Server 10 Installing the PHP engine 12 Configuring Abyss for PHP 14 Embedding PHP script

More information

Chapters 10 & 11 PHP AND MYSQL

Chapters 10 & 11 PHP AND MYSQL Chapters 10 & 11 PHP AND MYSQL Getting Started The database for a Web app would be created before accessing it from the web. Complete the design and create the tables independently. Use phpmyadmin, for

More information

COMP519: Web Programming Autumn 2015

COMP519: Web Programming Autumn 2015 COMP519: Web Programming Autumn 2015 In the next lectures you will learn What is SQL How to access mysql database How to create a basic mysql database How to use some basic queries How to use PHP and mysql

More information

CHAPTER 10. Connecting to Databases within PHP

CHAPTER 10. Connecting to Databases within PHP CHAPTER 10 Connecting to Databases within PHP CHAPTER OBJECTIVES Get a connection to a MySQL database from within PHP Use a particular database Send a query to the database Parse the query results Check

More information

MULTIMEDIA AND WEB TECHNOLOGY

MULTIMEDIA AND WEB TECHNOLOGY SET-4 Series GBM Code No. 89 Roll No. Candidates must write the Code on the title page of the answer-book. Please check that this question paper contains 9 printed pages. Code number given on the right

More information

Advanced Web Programming Practice Exam II

Advanced Web Programming Practice Exam II Advanced Web Programming Practice Exam II Name: 12 December 2017 This is a closed book exam. You may use one sheet of notes (8.5X11in, front only) but cannot use any other references or electronic device.

More information

Overview of MySQL Structure and Syntax [2]

Overview of MySQL Structure and Syntax [2] PHP PHP MySQL Database Overview of MySQL Structure and Syntax [2] MySQL is a relational database system, which basically means that it can store bits of information in separate areas and link those areas

More information

MULTIMEDIA AND WEB TECHNOLOGY

MULTIMEDIA AND WEB TECHNOLOGY SET 4 Series : GBM/1 Code No. 89/1 Roll No. Candidates must write the Code on the title page of the answer-book. Please check that this question paper contains 08 printed pages. Code number given on the

More information

MySQL and PHP - Developing Dynamic Web Applications

MySQL and PHP - Developing Dynamic Web Applications MySQL and PHP - Developing Dynamic Web Applications Student Guide SQL-4405 Rev 2.0 D62048GC10 Edition 1.0 D63883 Copyright 2010, Oracle and/or its affiliates. All rights reserved. Disclaimer This document

More information

MYSQL DATABASE ACCESS WITH PHP

MYSQL DATABASE ACCESS WITH PHP MYSQL DATABASE ACCESS WITH PHP Fall 2010 CSCI 2910 Server-Side Web Programming Typical web application interaction Database Server 3 tiered architecture Security in this interaction is critical Web Server

More information

The MANUAL. 1 P a g e

The MANUAL. 1 P a g e The MANUAL 1 P a g e http://wasimrlis.blogspot.in https://coprofessionals.wordpress.com 2 P a g e Guided to search tools are used to help library users to find the resources they are seeking. Originally

More information

ITC 250/CPET 499 Web Systems Nov. 3, 2016 Managing MySQL Database Part 3 of 3

ITC 250/CPET 499 Web Systems Nov. 3, 2016 Managing MySQL Database Part 3 of 3 ITC 250/CPET 499 Web Systems Nov. 3, 2016 Managing MySQL Database Part 3 of 3 MySQL Topics of Discussion More Command-Line Interface phpmyadmin o config.inc.php file : defineing a connection to the MySQL

More information

Use of PHP for DB Connection. Middle and Information Tier. Middle and Information Tier

Use of PHP for DB Connection. Middle and Information Tier. Middle and Information Tier Use of PHP for DB Connection 1 2 Middle and Information Tier PHP: built in library functions for interfacing with the mysql database management system $id = mysqli_connect(string hostname, string username,

More information

PHP Arrays. Lecture 20. Robb T. Koether. Hampden-Sydney College. Wed, Feb 28, 2018

PHP Arrays. Lecture 20. Robb T. Koether. Hampden-Sydney College. Wed, Feb 28, 2018 PHP Arrays Lecture 20 Robb T. Koether Hampden-Sydney College Wed, Feb 28, 2018 Robb T. Koether (Hampden-Sydney College) PHP Arrays Wed, Feb 28, 2018 1 / 27 1 PHP Arrays 2 Iteration Structures 3 Displaying

More information

SQL Commands & Mongo DB New Syllabus

SQL Commands & Mongo DB New Syllabus Chapter 15 : Computer Science Class XI ( As per CBSE Board) SQL Commands & Mongo DB New Syllabus 2018-19 SQL SQL is an acronym of Structured Query Language.It is a standard language developed and used

More information

CSCI-UA: Database Design & Web Implementation. Professor Evan Sandhaus

CSCI-UA: Database Design & Web Implementation. Professor Evan Sandhaus CSCI-UA:0060-02 Database Design & Web Implementation Professor Evan Sandhaus sandhaus@cs.nyu.edu evan@nytimes.com Lecture #28: This is the end - the only end my friends. Database Design and Web Implementation

More information

Use of PHP for DB Connection. Middle and Information Tier

Use of PHP for DB Connection. Middle and Information Tier Client: UI HTML, JavaScript, CSS, XML Use of PHP for DB Connection Middle Get all books with keyword web programming PHP Format the output, i.e., data returned from the DB SQL DB Query Access/MySQL 1 2

More information

If you do not specify any custom parameters, we will deliver the message using the default names.

If you do not specify any custom parameters, we will deliver the message using the default names. Inbound SMS to UK landline numbers API HTTP GET/POST variables If you choose to have the messages delivered by HTTP, you may either use our standard parameters, or create a custom format for compatibility

More information

Lecture 13: MySQL and PHP. Monday, March 26, 2018

Lecture 13: MySQL and PHP. Monday, March 26, 2018 Lecture 13: MySQL and PHP Monday, March 26, 2018 MySQL The Old Way In older versions of PHP, we typically used functions that started with mysql_ that did not belong to a class For example: o o o o mysql_connect()

More information

CPET 499/ITC 250 Web Systems

CPET 499/ITC 250 Web Systems CPET 499/ITC 250 Web Systems Chapter 11 Working with Databases Part 2 of 3 Text Book: * Fundamentals of Web Development, 2015, by Randy Connolly and Ricardo Hoar, published by Pearson Paul I-Hai, Professor

More information

PHP Querying. Lecture 21. Robb T. Koether. Hampden-Sydney College. Fri, Mar 2, 2018

PHP Querying. Lecture 21. Robb T. Koether. Hampden-Sydney College. Fri, Mar 2, 2018 PHP Querying Lecture 21 Robb T. Koether Hampden-Sydney College Fri, Mar 2, 2018 Robb T. Koether (Hampden-Sydney College) PHP Querying Fri, Mar 2, 2018 1 / 32 1 Connect to the Database 2 Querying the Database

More information

Chapter 1 An introduction to relational databases and SQL

Chapter 1 An introduction to relational databases and SQL Chapter 1 An introduction to relational databases and SQL Murach's MySQL, C1 2015, Mike Murach & Associates, Inc. Slide 1 Objectives Knowledge Identify the three main hardware components of a client/server

More information

XAMPP Web Development Stack

XAMPP Web Development Stack Overview @author R.L. Martinez, Ph.D. The steps below outline the processes for installing the XAMPP stack on a local machine. The XAMPP (pronounced Zamp) stack includes the following: Apache HTTP Server,

More information

Databases and PHP. Accessing databases from PHP

Databases and PHP. Accessing databases from PHP Databases and PHP Accessing databases from PHP PHP & Databases PHP can connect to virtuay any database There are specific functions buit-into PHP to connect with some DB There is aso generic ODBC functions

More information

Lab 7 Introduction to MySQL

Lab 7 Introduction to MySQL Lab 7 Introduction to MySQL Objectives: During this lab session, you will - Learn how to access the MySQL Server - Get hand-on experience on data manipulation and some PHP-to-MySQL technique that is often

More information

CSCE 548 Building Secure Software SQL Injection Attack

CSCE 548 Building Secure Software SQL Injection Attack CSCE 548 Building Secure Software SQL Injection Attack Professor Lisa Luo Spring 2018 Previous class DirtyCOW is a special type of race condition problem It is related to memory mapping We learned how

More information

Introduction to relational databases and MySQL

Introduction to relational databases and MySQL Chapter 3 Introduction to relational databases and MySQL A products table Columns 2017, Mike Murach & Associates, Inc. C3, Slide 1 2017, Mike Murach & Associates, Inc. C3, Slide 4 Objectives Applied 1.

More information

Systems Programming & Scripting

Systems Programming & Scripting Systems Programming & Scripting Lecture 19: Database Support Sys Prog & Scripting - HW Univ 1 Typical Structure of a Web Application Client Internet Web Server Application Server Database Server Third

More information

Options. Real SQL Programming 1. Stored Procedures. Embedded SQL

Options. Real SQL Programming 1. Stored Procedures. Embedded SQL Real 1 Options We have seen only how SQL is used at the generic query interface an environment where we sit at a terminal and ask queries of a database. Reality is almost always different: conventional

More information

tablename ORDER BY column ASC tablename ORDER BY column DESC sortingorder, } The WHERE and ORDER BY clauses can be combined in one

tablename ORDER BY column ASC tablename ORDER BY column DESC sortingorder, } The WHERE and ORDER BY clauses can be combined in one } The result of a query can be sorted in ascending or descending order using the optional ORDER BY clause. The simplest form of an ORDER BY clause is SELECT columnname1, columnname2, FROM tablename ORDER

More information

Linux Network Administration. MySQL COMP1071 Summer 2017

Linux Network Administration. MySQL COMP1071 Summer 2017 Linux Network Administration MySQL COMP1071 Summer 2017 Databases Database is a term used to describe a collection of structured data A database software package contains the tools used to store, access,

More information

Implementing Table Operations Using Structured Query Language (SQL) Using Multiple Operations. SQL: Structured Query Language

Implementing Table Operations Using Structured Query Language (SQL) Using Multiple Operations. SQL: Structured Query Language Implementing Table Operations Using Structured Query Language (SQL) Using Multiple Operations Show Only certain columns and rows from the join of Table A with Table B The implementation of table operations

More information

School of Information and Computer Technology Sirindhorn International Institute of Technology Thammasat University

School of Information and Computer Technology Sirindhorn International Institute of Technology Thammasat University School of Information and Computer Technology Sirindhorn International Institute of Technology Thammasat University ITS351 Database Programming Laboratory Laboratory #9: PHP & Form Processing III Objective:

More information

Lecture 5. Monday, September 15, 2014

Lecture 5. Monday, September 15, 2014 Lecture 5 Monday, September 15, 2014 The MySQL Command So far, we ve learned some parts of the MySQL command: mysql [database] [-u username] p [-- local-infile]! Now let s go further 1 mysqldump mysqldump

More information

CSCI 4000 Assignment 4

CSCI 4000 Assignment 4 Austin Peay State University, Tennessee Spring 2018 CSCI 4000: Advanced Web Development Dr. Leong Lee CSCI 4000 Assignment 4 Total estimated time for this assignment: 12 hours (if you are a good programmer)

More information

CMPS 401 Survey of Programming Languages

CMPS 401 Survey of Programming Languages CMPS 401 Survey of Programming Languages Programming Assignment #4 PHP Language On the Ubuntu Operating System Write a PHP program (P4.php) and create a HTML (P4.html) page under the Ubuntu operating system.

More information

IELM 511 Information Systems Design Labs 5 and 6. DB creation and Population

IELM 511 Information Systems Design Labs 5 and 6. DB creation and Population IELM 511 Information Systems Design Labs 5 and 6. DB creation and Population In this lab, your objective is to learn the basics of creating and managing a DB system. One way to interact with the DBMS (MySQL)

More information

Princess Nourah bint Abdulrahman University. Computer Sciences Department

Princess Nourah bint Abdulrahman University. Computer Sciences Department Princess Nourah bint Abdulrahman University Computer Sciences Department 1 And use http://www.w3schools.com/ PHP Part 3 Objectives Creating a new MySQL Database using Create & Check connection with Database

More information

The PHP language. Teaching you everything about PHP? Not exactly Goal: teach you how to interact with a database via web

The PHP language. Teaching you everything about PHP? Not exactly Goal: teach you how to interact with a database via web Web programming The PHP language Our objective Teaching you everything about PHP? Not exactly Goal: teach you how to interact with a database via web Access data inserted by users into HTML forms Interact

More information

30. Structured Query Language (SQL)

30. Structured Query Language (SQL) 30. Structured Query Language (SQL) Java Fall 2009 Instructor: Dr. Masoud Yaghini Outline SQL query keywords Basic SELECT Query WHERE Clause ORDER BY Clause INNER JOIN Clause INSERT Statement UPDATE Statement

More information

SQL stands for Structured Query Language. SQL lets you access and manipulate databases

SQL stands for Structured Query Language. SQL lets you access and manipulate databases CMPSC 117: WEB DEVELOPMENT SQL stands for Structured Query Language SQL lets you access and manipulate databases SQL is an ANSI (American National Standards Institute) standard 1 SQL can execute queries

More information

Databases PHP I. (GF Royle, N Spadaccini ) PHP I 1 / 24

Databases PHP I. (GF Royle, N Spadaccini ) PHP I 1 / 24 Databases PHP I (GF Royle, N Spadaccini 2006-2010) PHP I 1 / 24 This lecture This covers the (absolute) basics of PHP and how to connect to a database using MDB2. (GF Royle, N Spadaccini 2006-2010) PHP

More information

CSCI 4000 Assignment 6

CSCI 4000 Assignment 6 Austin Peay State University, Tennessee Spring 2018 CSCI 4000: Advanced Web Development Dr. Leong Lee CSCI 4000 Assignment 6 Total estimated time for this assignment: 6 hours (if you are a good programmer)

More information

School of Information and Computer Technology Sirindhorn International Institute of Technology Thammasat University

School of Information and Computer Technology Sirindhorn International Institute of Technology Thammasat University School of Information and Computer Technology Sirindhorn International Institute of Technology Thammasat University ITS331 Information Technology Laboratory I Laboratory #8: PHP & Form Processing II Objective:

More information

Introduction to web development with PHP

Introduction to web development with PHP Chapter 1 Introduction to web development with PHP Objectives (continued) Knowledge 9. Describe the benefits of using an IDE like NetBeans for application development. 2017, Mike Murach & Associates, Inc.

More information

Chapter 13 : Informatics Practices. Class XI ( As per CBSE Board) SQL Commands. New Syllabus Visit : python.mykvs.in for regular updates

Chapter 13 : Informatics Practices. Class XI ( As per CBSE Board) SQL Commands. New Syllabus Visit : python.mykvs.in for regular updates Chapter 13 : Informatics Practices Class XI ( As per CBSE Board) SQL Commands New Syllabus 2018-19 SQL SQL is an acronym of Structured Query Language.It is a standard language developed and used for accessing

More information

Databases and MySQL: The Basics

Databases and MySQL: The Basics Databases and MySQL: The Basics CISC 282 November 8, 2017 Definitions Database "Collection of related facts" (Pat Martin, CISC 332) Organized data set Used for large quantities of information Relational

More information

Chapter 3. Introduction to relational databases and MySQL. 2010, Mike Murach & Associates, Inc. Murach's PHP and MySQL, C3

Chapter 3. Introduction to relational databases and MySQL. 2010, Mike Murach & Associates, Inc. Murach's PHP and MySQL, C3 1 Chapter 3 Introduction to relational databases and MySQL Slide 2 Objectives Applied 1. Use phpmyadmin to review the data and structure of the tables in a database, to import and run SQL scripts that

More information

Today Learning outcomes LO2

Today Learning outcomes LO2 2015 2016 Phil Smith Today Learning outcomes LO2 On successful completion of this unit you will: 1. Be able to design and implement relational database systems. 2. Requirements. 3. User Interface. I am

More information

Automatic MySQL Schema Management with Skeema. Evan Elias Percona Live, April 2017

Automatic MySQL Schema Management with Skeema. Evan Elias Percona Live, April 2017 Automatic MySQL Schema Management with Skeema Evan Elias Percona Live, April 2017 What is Schema Management? Organize table schemas in a repo Execution of all DDL, on the correct MySQL instances, with

More information

GIFT Department of Computing Science Data Selection and Filtering using the SELECT Statement

GIFT Department of Computing Science Data Selection and Filtering using the SELECT Statement GIFT Department of Computing Science [Spring 2013] CS-217: Database Systems Lab-2 Manual Data Selection and Filtering using the SELECT Statement V1.0 4/12/2016 Introduction to Lab-2 This lab reinforces

More information

Lecture 7: Web hacking 3, SQL injection, Xpath injection, Server side template injection, File inclusion

Lecture 7: Web hacking 3, SQL injection, Xpath injection, Server side template injection, File inclusion IN5290 Ethical Hacking Lecture 7: Web hacking 3, SQL injection, Xpath injection, Server side template injection, File inclusion Universitetet i Oslo Laszlo Erdödi Lecture Overview What is SQL injection

More information

This lecture. PHP tags

This lecture. PHP tags This lecture Databases I This covers the (absolute) basics of and how to connect to a database using MDB2. (GF Royle 2006-8, N Spadaccini 2008) I 1 / 24 (GF Royle 2006-8, N Spadaccini 2008) I 2 / 24 What

More information

CGS 3066: Spring 2017 SQL Reference

CGS 3066: Spring 2017 SQL Reference CGS 3066: Spring 2017 SQL Reference Can also be used as a study guide. Only covers topics discussed in class. This is by no means a complete guide to SQL. Database accounts are being set up for all students

More information

PHP Tutorial 6(a) Using PHP with MySQL

PHP Tutorial 6(a) Using PHP with MySQL Objectives After completing this tutorial, the student should have learned; The basic in calling MySQL from PHP How to display data from MySQL using PHP How to insert data into MySQL using PHP Faculty

More information

SSE 3200 Mysql lab. Introduction. Getting started

SSE 3200 Mysql lab. Introduction. Getting started SSE 3200 Mysql lab Introduction SQL (Structured Query Language) is a standard language for creating, accessing, and manipulating databases. A database is a collection of tables. Each table consists of

More information

Chapter-14 SQL COMMANDS

Chapter-14 SQL COMMANDS Chapter-14 SQL COMMANDS What is SQL? Structured Query Language and it helps to make practice on SQL commands which provides immediate results. SQL is Structured Query Language, which is a computer language

More information

Instructor s Notes Web Data Management Web Client/Server Concepts. Web Data Management Web Client/Server Concepts

Instructor s Notes Web Data Management Web Client/Server Concepts. Web Data Management Web Client/Server Concepts Instructor s Web Data Management Web Client/Server Concepts Web Data Management 152-155 Web Client/Server Concepts Quick Links & Text References Client / Server Concepts Pages 4 11 Web Data Mgt Software

More information

Using PHP to Plot PART I Updated: 10/1/17

Using PHP to Plot PART I Updated: 10/1/17 Using PHP to Plot PART I Updated: 10/1/17 A. Objectives Learn about Dynamic URL Request Learn about curl and HTTP Request Methods How to access and FTP server automatically How to use sshpass and scp Understanding

More information

Chapter 9: MySQL for Server-Side Data Storage

Chapter 9: MySQL for Server-Side Data Storage Chapter 9: MySQL for Server-Side Data Storage General Notes on the Slides for This Chapter In many slides you will see webbook as a database name. That was the orginal name of our database. For this second

More information

Model Question Paper. Credits: 4 Marks: 140

Model Question Paper. Credits: 4 Marks: 140 Model Question Paper Subject Code: BT0075 Subject Name: RDBMS and MySQL Credits: 4 Marks: 140 Part A (One mark questions) 1. MySQL Server works in A. client/server B. specification gap embedded systems

More information

Chapter 1. Introduction to web development and PHP. 2010, Mike Murach & Associates, Inc. Murach's PHP and MySQL, C1

Chapter 1. Introduction to web development and PHP. 2010, Mike Murach & Associates, Inc. Murach's PHP and MySQL, C1 1 Chapter 1 Introduction to web development and PHP 2 Applied Objectives Use the XAMPP control panel to start or stop Apache or MySQL when it is running on your own computer. Deploy a PHP application on

More information

Course Outline. MySQL Database Administration & Design. Course Description: Pre-requisites: Course Content:

Course Outline. MySQL Database Administration & Design. Course Description: Pre-requisites: Course Content: MySQL Database Administration & Design Course Description: MySQL is the open source community's most popular Relational Database Management System (RDBMS) offering, and is a key part of LAMP - Linux, Apache,

More information

Executing Simple Queries

Executing Simple Queries Script 8.3 The registration script adds a record to the database by running an INSERT query. 1

More information

Kaivos User Guide Getting a database account 2

Kaivos User Guide Getting a database account 2 Contents Kaivos User Guide 1 1. Getting a database account 2 2. MySQL client programs at CSC 2 2.1 Connecting your database..................................... 2 2.2 Setting default values for MySQL connection..........................

More information

COM1004 Web and Internet Technology

COM1004 Web and Internet Technology COM1004 Web and Internet Technology When a user submits a web form, how do we save the information to a database? How do we retrieve that data later? ID NAME EMAIL MESSAGE TIMESTAMP 1 Mike mike@dcs Hi

More information

Mysql Tutorial Create Database User Grant All Specification

Mysql Tutorial Create Database User Grant All Specification Mysql Tutorial Create Database User Grant All Specification The world's most popular open source database This part of CREATE USER syntax is shared with GRANT, so the description here applies to GRANT

More information

Programming for the Web with PHP

Programming for the Web with PHP Aptech Ltd Version 1.0 Page 1 of 11 Table of Contents Aptech Ltd Version 1.0 Page 2 of 11 Abstraction Anonymous Class Apache Arithmetic Operators Array Array Identifier arsort Function Assignment Operators

More information

chapter 2 G ETTING I NFORMATION FROM A TABLE

chapter 2 G ETTING I NFORMATION FROM A TABLE chapter 2 Chapter G ETTING I NFORMATION FROM A TABLE This chapter explains the basic technique for getting the information you want from a table when you do not want to make any changes to the data and

More information

Creating Your First MySQL Database. Scott Seighman Sales Consultant Oracle

Creating Your First MySQL Database. Scott Seighman Sales Consultant Oracle Creating Your First MySQL Database Scott Seighman Sales Consultant Oracle Agenda Installation Review Accessing the MySQL Server > Command Line > GUI Tools/MySQL Workbench 5.2 Creating Your First Database

More information

Welcome to Cole On-line Help system!

Welcome to Cole On-line Help system! Welcome to Cole On-line Help system! Cole Online is an Internet based information directory that allows fast and efficient access to demographic information about residences and businesses. You can search

More information

SQL BASICS WITH THE SMALLBANKDB STEFANO GRAZIOLI & MIKE MORRIS

SQL BASICS WITH THE SMALLBANKDB STEFANO GRAZIOLI & MIKE MORRIS SQL BASICS WITH THE SMALLBANKDB STEFANO GRAZIOLI & MIKE MORRIS This handout covers the most important SQL statements. The examples provided throughout are based on the SmallBank database discussed in class.

More information

PHP Reference. To access MySQL manually, run the following command on the machine, called Sources, where MySQL and PhP have been installed:

PHP Reference. To access MySQL manually, run the following command on the machine, called Sources, where MySQL and PhP have been installed: PHP Reference 1 Preface This tutorial is designed to teach you all the PHP commands and constructs you need to complete your PHP project assignment. It is assumed that you have never programmed in PHP

More information

How To Start Mysql Use Linux Command Line Client In Xampp

How To Start Mysql Use Linux Command Line Client In Xampp How To Start Mysql Use Linux Command Line Client In Xampp It also assumes that you're familiar with the MySQL command-line client and that you And since both Amazon and Bitnami have a free tier, you can

More information

Jarek Szlichta

Jarek Szlichta Jarek Szlichta http://data.science.uoit.ca/ SQL is a standard language for accessing and manipulating databases What is SQL? SQL stands for Structured Query Language SQL lets you gain access and control

More information

Mastering phpmyadmiri 3.4 for

Mastering phpmyadmiri 3.4 for Mastering phpmyadmiri 3.4 for Effective MySQL Management A complete guide to getting started with phpmyadmin 3.4 and mastering its features Marc Delisle [ t]open so 1 I community experience c PUBLISHING

More information

Static Webpage Development

Static Webpage Development Dear Student, Based upon your enquiry we are pleased to send you the course curriculum for PHP Given below is the brief description for the course you are looking for: - Static Webpage Development Introduction

More information