40
PHP Penn Wu, PhD 323 Lecture #12 PHP and MySQL (MariaDB) Introduction 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 open- source relational database management system (RDBMS) with SQLbeing 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. 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 1994. 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 Client browser Apache server PHP interpreter MySQL server

SELECT FROM Orders WHERE Amount > 200;students.cypresscollege.edu/cis246/lc12.pdfcode base as MySQL server 5.5 and aims to maintain compatibility with Oracle-owned MySQL version. Seeing

  • Upload
    others

  • View
    8

  • Download
    0

Embed Size (px)

Citation preview

Page 1: SELECT FROM Orders WHERE Amount > 200;students.cypresscollege.edu/cis246/lc12.pdfcode base as MySQL server 5.5 and aims to maintain compatibility with Oracle-owned MySQL version. Seeing

PHP – Penn Wu, PhD

323

Lecture #12 PHP and MySQL (MariaDB)

Introduction

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 open-

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

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

Client

browser Apache

server

PHP

interpreter

MySQL

server

Page 2: SELECT FROM Orders WHERE Amount > 200;students.cypresscollege.edu/cis246/lc12.pdfcode base as MySQL server 5.5 and aims to maintain compatibility with Oracle-owned MySQL version. Seeing

PHP – Penn Wu, PhD

324

following table, the instructor purposely uses uppercase to distinguish SQL commands from other

components (such as tableName).

Command Description CREATE DATABASE databaseName creates a new database CREATE TABLE tableName creates a new table SELECT FROM tableName extracts data from a database INSERT INTO tableName inserts new data into a database DROP TABLE tableName deletes a table UPDATE tableName SET updates data in a database DELETE FROM tableName 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”, “8182243654”, and “Long Beach” are records of “Mike Smith”.

+-----+--------------+----------------------+----------+------------+------------+

| CID | name | address | zip code | phone | city |

+-----+--------------+----------------------+----------+------------+------------+

| 101 | Mike Smith | 23 Workhaven Lane | 90630 | 8182243654 | Long Beach |

| 102 | Ann McDonald | 1411 Lillydale Drive | 91273 | 6172235589 | 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.

Page 3: SELECT FROM Orders WHERE Amount > 200;students.cypresscollege.edu/cis246/lc12.pdfcode base as MySQL server 5.5 and aims to maintain compatibility with Oracle-owned MySQL version. Seeing

PHP – Penn Wu, PhD

325

Welcome to the MariaDB monitor. Commands end with ; or \g.

Your MariaDB connection id is 2

Server version: 10.1.13-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 |

+--------------------+

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

based 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”.

Page 4: SELECT FROM Orders WHERE Amount > 200;students.cypresscollege.edu/cis246/lc12.pdfcode base as MySQL server 5.5 and aims to maintain compatibility with Oracle-owned MySQL version. Seeing

PHP – Penn Wu, PhD

326

port: This is an optional parameter. If not assigned, the value is automatically set to 3800. By

default, MySQL server uses port 3800. However, the network administrator might choose to

use a different port, such as 3801.

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.

<?php

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

<?php

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

<?php

$conn = new mysqli('localhost', 'tcm159', 'sGkY4651',

'Customers');

if ($conn->connect_error)

{

die($conn->connect_errno . ': ' . $conn->connect_error);

}

else

{

echo 'Success... ' . $conn->host_info . "<br>";

}

$conn->close();

?>

Page 5: SELECT FROM Orders WHERE Amount > 200;students.cypresscollege.edu/cis246/lc12.pdfcode base as MySQL server 5.5 and aims to maintain compatibility with Oracle-owned MySQL version. Seeing

PHP – Penn Wu, PhD

327

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.

<?php

$conn = mysqli_connect('localhost', 'tcm159', 'sGkY4651',

'Customers');

if (mysqli_connect_error()) {

die(mysqli_connect_errno() . ': ' . mysqli_connect_error());

}

else

{

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 Procedural if ($conn->connect_error)

{

die("Connection failed.");

}

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:

<?php

$conn = mysqli_connect('localhost', 'tcm159', 'sGkY4651',

'Customers');

if (!$conn) {

die(mysqli_connect_errno() . ': ' . mysqli_connect_error());

}

else

{

echo 'Success... ' . mysqli_get_host_info($conn) . "\n";

}

mysqli_close($conn);

?>

Page 6: SELECT FROM Orders WHERE Amount > 200;students.cypresscollege.edu/cis246/lc12.pdfcode base as MySQL server 5.5 and aims to maintain compatibility with Oracle-owned MySQL version. Seeing

PHP – Penn Wu, PhD

328

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.

<?php

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

<?php

$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

<?php

$conn = new mysqli('localhost', 'tcm159', 'SGkY4651',

'Customers');

...........

$mysqli->select_db("Client"); // change to Client database

...........

?>

The following is the procedural version.

<?php

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

Page 7: SELECT FROM Orders WHERE Amount > 200;students.cypresscollege.edu/cis246/lc12.pdfcode base as MySQL server 5.5 and aims to maintain compatibility with Oracle-owned MySQL version. Seeing

PHP – Penn Wu, PhD

329

The following is a complete sample code.

<?php

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

}

else

{

$sql = "SELECT * FROM ContactPerson";

$result = $conn->query($sql);

if ($result)

{

echo "Return ". $result->num_rows . " record(s)";

$result->close(); // free the result data set

}

else

{

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.

<?php

$conn = new mysqli('localhost', 'tcm159', 'sGkY4651',

'Endusers');

if ($conn->connect_error)

{

die($conn->connect_errno . ': ' . $conn->connect_error);

}

else

{

$sql = "SELECT * FROM Tickets";

$result = $conn->query($sql);

if ($result)

Page 8: SELECT FROM Orders WHERE Amount > 200;students.cypresscollege.edu/cis246/lc12.pdfcode base as MySQL server 5.5 and aims to maintain compatibility with Oracle-owned MySQL version. Seeing

PHP – Penn Wu, PhD

330

{

echo "Return " . $result->num_rows . " record(s)";

$result->close(); // free the result data set

}

else

{

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.

<?php

$conn = mysqli_connect('localhost', 'tcm159', 'sGkY4651',

'Endusers');

if (!$conn) {

die(mysqli_connect_errno() . ': ' . mysqli_connect_error());

}

else

{

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

Page 9: SELECT FROM Orders WHERE Amount > 200;students.cypresscollege.edu/cis246/lc12.pdfcode base as MySQL server 5.5 and aims to maintain compatibility with Oracle-owned MySQL version. Seeing

PHP – Penn Wu, PhD

331

fetch_assoc() mysqli_fetch_assoc() Fetches a result row as an associative array.

fetch_array() mysqli_fetch_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 4842154261

Row 1 A1025 MathWorks Corp. Betty Simens 9513375483

Row 2 A1039 SouthDame Co. Anna Ariel 6065249744

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, 4842154261

A1025, MathWorks Corp., Betty Simens, 9513375483

A1039, SouthDame Co., Anna Ariel ,6065249744

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.

<?php

$conn = mysqli_connect('localhost', 'tcm159', 'sGkY4651',

'Customers');

if (!$conn) {

die(mysqli_connect_errno() . ': ' . mysqli_connect_error());

}

else

{

$sql = "SELECT * FROM Company";

$result = mysqli_query($conn, $sql);

if ($result)

Page 10: SELECT FROM Orders WHERE Amount > 200;students.cypresscollege.edu/cis246/lc12.pdfcode base as MySQL server 5.5 and aims to maintain compatibility with Oracle-owned MySQL version. Seeing

PHP – Penn Wu, PhD

332

{

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

}

else

{

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"=>"4842154261");

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

}

Page 11: SELECT FROM Orders WHERE Amount > 200;students.cypresscollege.edu/cis246/lc12.pdfcode base as MySQL server 5.5 and aims to maintain compatibility with Oracle-owned MySQL version. Seeing

PHP – Penn Wu, PhD

333

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

Page 12: SELECT FROM Orders WHERE Amount > 200;students.cypresscollege.edu/cis246/lc12.pdfcode base as MySQL server 5.5 and aims to maintain compatibility with Oracle-owned MySQL version. Seeing

PHP – Penn Wu, PhD

334

{

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

Page 13: SELECT FROM Orders WHERE Amount > 200;students.cypresscollege.edu/cis246/lc12.pdfcode base as MySQL server 5.5 and aims to maintain compatibility with Oracle-owned MySQL version. Seeing

PHP – Penn Wu, PhD

335

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.

<?php

$conn = mysqli_connect('localhost', 'tcm159', 'sGkY4651',

'Customers');

if (!$conn) {

die(mysqli_connect_errno() . ': ' . mysqli_connect_error());

}

else

{

$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

}

else

{

die(mysqli_error($conn));

}

}

mysqli_close($conn);

?>

A sample output looks:

Page 14: SELECT FROM Orders WHERE Amount > 200;students.cypresscollege.edu/cis246/lc12.pdfcode base as MySQL server 5.5 and aims to maintain compatibility with Oracle-owned MySQL version. Seeing

PHP – Penn Wu, PhD

336

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, “D0012547”. 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='D0012547';

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='D0012547';"

$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='DB16-

10041';";

$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

S310221 A1012 2025-10-21

S310222 A1097 2025-10-21

S310223 A1039 2025-10-21

S310224 A1043 2025-10-21

S310225 A1039 2025-10-21

S310226 A1064 2025-10-21

S310227 A1039 2025-10-21

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 |

+-----------+

Page 15: SELECT FROM Orders WHERE Amount > 200;students.cypresscollege.edu/cis246/lc12.pdfcode base as MySQL server 5.5 and aims to maintain compatibility with Oracle-owned MySQL version. Seeing

PHP – Penn Wu, PhD

337

| S310223 |

+-----------+

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 Example INSERT INTO tableName INSERT INTO Payments VALUES ('A1012', 'CreditCard',

'Net15');

DROP TABLE tableName DROP TABLE Payments;

UPDATE tableName SET UPDATE Payments SET option2='Net10' WHERE

cid='A1012';

DELETE FROM tableName 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”.

<?php

$conn = new mysqli('localhost', 'tcm159', 'sGkY4651',

'Endusers');

if ($conn->connect_error) { die("Connection failed."); }

else {

$sql = "INSERT INTO tickets VALUES ('DB16-56721', 'Sue', 'Yuan',

'[email protected]', 0);";

$result = $conn->query($sql) or die("Error");

}

$conn->close();

?>

The following is another object-oriented code that demonstrates how to update a record.

Page 16: SELECT FROM Orders WHERE Amount > 200;students.cypresscollege.edu/cis246/lc12.pdfcode base as MySQL server 5.5 and aims to maintain compatibility with Oracle-owned MySQL version. Seeing

PHP – Penn Wu, PhD

338

<?php

$conn = new mysqli('localhost', 'tcm159', 'sGkY4651',

'Endusers');

if ($conn->connect_error) { die("Connection failed."); }

else {

$sql = "UPDATE tickets SET lastname='Yen' WHERE TicketNo='DB16-

56721';";

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

<?php

$conn = mysqli_connect('localhost', 'tcm159', 'sGkY4651',

'Endusers');

if (!$conn) { die("Connection failed."); }

else {

$sql = "delete from tickets where ticketno='DB16-56721';";

$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 = 'DB16-

980561';

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

Page 17: SELECT FROM Orders WHERE Amount > 200;students.cypresscollege.edu/cis246/lc12.pdfcode base as MySQL server 5.5 and aims to maintain compatibility with Oracle-owned MySQL version. Seeing

PHP – Penn Wu, PhD

339

}

else

{

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.

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

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

Company

A1039

SouthDame Co.

Anna Ariel 6065249744

1012 Main St.

West Hills CA

2025-11-04

Orders

S310225

A1039 2025-10-21

2025-10-21

2603.41 0.00

2025-11-15

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

Page 18: SELECT FROM Orders WHERE Amount > 200;students.cypresscollege.edu/cis246/lc12.pdfcode base as MySQL server 5.5 and aims to maintain compatibility with Oracle-owned MySQL version. Seeing

PHP – Penn Wu, PhD

340

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

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

<?php

if ($_POST)

{

$cid = $_POST['cid'];

$conn = mysqli_connect('localhost', 'tcm159', 'sGkY4651',

'Customers');

if (!$conn) {

die(mysqli_connect_errno() . ': ' . mysqli_connect_error());

}

else

PaymentMethod …..

A1039

…….

Company …..

A1039

…….

Orders …..

A1039

…….

Page 19: SELECT FROM Orders WHERE Amount > 200;students.cypresscollege.edu/cis246/lc12.pdfcode base as MySQL server 5.5 and aims to maintain compatibility with Oracle-owned MySQL version. Seeing

PHP – Penn Wu, PhD

341

{

$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

}

else

{

die("No record found with <b>'" . $cid . "'</b>.");

}

}

mysqli_close($conn);

}

else

{

?>

<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">

Customer ID: <input type="text" name="cid">

<input type="submit" value="Submit">

</form>

<?php } ?>

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.

Page 20: SELECT FROM Orders WHERE Amount > 200;students.cypresscollege.edu/cis246/lc12.pdfcode base as MySQL server 5.5 and aims to maintain compatibility with Oracle-owned MySQL version. Seeing

PHP – Penn Wu, PhD

342

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.

ISBN Author Publisher

9485753572 Lucy Chen Apex Inc.

9485753573 Helen Smith Braun Publishing Corp.

9485753574 Terrie Garcia Oxmoore House

A. $k=0; echo $row[$k];

B. $k="ISBN"; echo $row[$k[0]];

C. echo $row[0];

D. echo $row['ISBN'];

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

Page 21: SELECT FROM Orders WHERE Amount > 200;students.cypresscollege.edu/cis246/lc12.pdfcode base as MySQL server 5.5 and aims to maintain compatibility with Oracle-owned MySQL version. Seeing

PHP – Penn Wu, PhD

343

9485753572 Lucy Chen Apex Inc.

9485753573 Helen Smith Braun Publishing Corp.

9485753574 Terrie Garcia Oxmoore House

A. 9485753572, 9485753573, 9485753574

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

9485753572 Lucy Chen Apex Inc.

9485753573 Helen Smith Braun Publishing Corp.

9485753574 Terrie Garcia Oxmoore House

A. ISBN, Author, Publisher

B. 9485753572, 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 "DB16-10041" 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 = 'DB16-10041';";

$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"];

Page 22: SELECT FROM Orders WHERE Amount > 200;students.cypresscollege.edu/cis246/lc12.pdfcode base as MySQL server 5.5 and aims to maintain compatibility with Oracle-owned MySQL version. Seeing

PHP – Penn Wu, PhD

344

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!

Press any key to continue . . .

Do you want to refresh the XAMPP installation?

1) Refresh now!

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

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

Page 23: SELECT FROM Orders WHERE Amount > 200;students.cypresscollege.edu/cis246/lc12.pdfcode base as MySQL server 5.5 and aims to maintain compatibility with Oracle-owned MySQL version. Seeing

PHP – Penn Wu, PhD

345

@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: 10.1.10-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 |

+--------------------+

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

Page 24: SELECT FROM Orders WHERE Amount > 200;students.cypresscollege.edu/cis246/lc12.pdfcode base as MySQL server 5.5 and aims to maintain compatibility with Oracle-owned MySQL version. Seeing

PHP – Penn Wu, PhD

346

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 |

+--------------------+

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

+---------------------+

3 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 | 4842154261 | 17895 Via San Pedro St. | Long Beach |

CA | 0000-00-00 |

| A1025 | MathWorks Corp. | Betty Simens | 9513375483 | 22157 Anderson Blvd. | Pomona |

CA | 0000-00-00 |

| A1039 | SouthDame Co. | Anna Ariel | 6065249744 | 1012 Main St. | West Hills |

CA | 0000-00-00 |

| A1043 | Eastern Technology | Jenny Ngo | 8180214563 | 4329 Kimberly Court | Cypress |

CA | 0000-00-00 |

| A1056 | Aspen Sciences. | Erica Strickland | 2134847211 | 9120 Hackbart Rd. | Irvine |

CA | 0000-00-00 |

| A1064 | Harazawa Foods. | Mariko Yamada | 7146358527 | 17652 Central Ave. | Long Beach |

CA | 0000-00-00 |

Page 25: SELECT FROM Orders WHERE Amount > 200;students.cypresscollege.edu/cis246/lc12.pdfcode base as MySQL server 5.5 and aims to maintain compatibility with Oracle-owned MySQL version. Seeing

PHP – Penn Wu, PhD

347

| A1078 | Tong Hai Precisions. | Linda Zhao | 4157412836 | 22336 Wiley Dr. | Diamond Bar |

CA | 0000-00-00 |

| A1081 | Worcester Institute | Stacy Barger | 4506225014 | 11438 Glory St. | Chino Hills |

CA | 0000-00-00 |

| A1097 | Texas Watches | Lucy Park | 7013438983 | 396 Spectrum Parkway | Irvine |

CA | 0000-00-00 |

+-------+----------------------+------------------+-------------+-------------------------+-------------+--

-----+-------------------+

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

<?php

$conn = mysqli_connect('localhost', 'tcm159', 'sGkY4651', 'Customers');

if (!$conn) {

die(mysqli_connect_errno() . ': ' . mysqli_connect_error());

}

else

{

$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

}

else

{

die(mysqli_error($conn));

}

}

mysqli_close($conn);

?>

2. Test the program. A sample output looks like:

Page 26: SELECT FROM Orders WHERE Amount > 200;students.cypresscollege.edu/cis246/lc12.pdfcode base as MySQL server 5.5 and aims to maintain compatibility with Oracle-owned MySQL version. Seeing

PHP – Penn Wu, PhD

348

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>

<?php

if ($_POST)

{

$cid = $_POST['cid'];

$conn = mysqli_connect('localhost', 'tcm159', 'sGkY4651', 'Customers');

if (!$conn) {

die(mysqli_connect_errno() . ': ' . mysqli_connect_error());

}

else

{

$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

Page 27: SELECT FROM Orders WHERE Amount > 200;students.cypresscollege.edu/cis246/lc12.pdfcode base as MySQL server 5.5 and aims to maintain compatibility with Oracle-owned MySQL version. Seeing

PHP – Penn Wu, PhD

349

}

else

{

die("No record found with <b>'" . $cid . "'</b>.");

}

}

mysqli_close($conn);

}

else

{

?>

<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">

Customer ID: <input type="text" name="cid"><br>

<input type="submit" value="Submit">

</form>

<?php } ?>

</body>

</html>

2. Test the program. A sample output looks like:

and

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>

<?php

if ($_POST)

{

$cid = $_POST['cid'];

$conn = mysqli_connect('localhost', 'tcm159', 'sGkY4651', 'Customers');

if (!$conn) {

die(mysqli_connect_errno() . ': ' . mysqli_connect_error());

}

else

Page 28: SELECT FROM Orders WHERE Amount > 200;students.cypresscollege.edu/cis246/lc12.pdfcode base as MySQL server 5.5 and aims to maintain compatibility with Oracle-owned MySQL version. Seeing

PHP – Penn Wu, PhD

350

{

/////// 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

}

else

{

die("No record found with <b>'" . $cid . "'</b>.");

}

/////// query 2 /////////

mysqli_select_db($conn, "Clients");

if (!$conn) { die("Connecting to 'Clients' database failed."); }

else

{

$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>";

Page 29: SELECT FROM Orders WHERE Amount > 200;students.cypresscollege.edu/cis246/lc12.pdfcode base as MySQL server 5.5 and aims to maintain compatibility with Oracle-owned MySQL version. Seeing

PHP – Penn Wu, PhD

351

///// 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

}

else

{

die("No record found with <b>'" . $cid . "'</b>.");

}

}

}

mysqli_close($conn);

}

else

{

?>

<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">

Customer ID: <input type="text" name="cid"><br>

<input type="submit" value="Submit">

</form>

<?php } ?>

</body>

</html>

2. Test the program. A sample output looks like:

and

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 #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'>

Page 30: SELECT FROM Orders WHERE Amount > 200;students.cypresscollege.edu/cis246/lc12.pdfcode base as MySQL server 5.5 and aims to maintain compatibility with Oracle-owned MySQL version. Seeing

PHP – Penn Wu, PhD

352

<form name="form1" action="<?php 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'>Email: </td><td><input type="text" name="email"></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>

<?php

if ($_POST)

{

$action = $_POST['action'];

$fname = $_POST['fname'];

$lname = $_POST['lname'];

$email = $_POST['email'];

$ticketno = $_POST['ticketno'];

switch (strtolower($action))

{

case "insert": insertData($fname, $lname, $email); break;

case "update": updateData($fname, $lname, $email, $ticketno); break;

case "delete": deleteData($ticketno); break;

}

$_POST=NULL;

}

//////// function for insert /////////

function insertData($fname, $lname, $email)

{

$conn = mysqli_connect('localhost', 'tcm159', 'sGkY4651', 'Endusers');

if (!$conn) {

die("Cannot access the database.");

}

else

{

$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 98052 to lastTIcketNo

Page 31: SELECT FROM Orders WHERE Amount > 200;students.cypresscollege.edu/cis246/lc12.pdfcode base as MySQL server 5.5 and aims to maintain compatibility with Oracle-owned MySQL version. Seeing

PHP – Penn Wu, PhD

353

$lastTicketNo++; // increment by 1

$newticketno = $prefix . "-" . $lastTicketNo;

mysqli_free_result($result);

}

else { die("No existing ticket number."); }

/////////// insert data ////////////

$sql = "INSERT INTO tickets VALUES ('" . $newticketno ."', '" . $fname . "', '" .

$lname . "', '" . $email. "', 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>Email: $email</li>";

echo "<li>Flag: 0</ul></p>";

}

else { die("Data inserting failed."); }

}

mysqli_close($conn);

}

///////// function for update ///////////

function updateData($fname, $lname, $email, $ticketno)

{

$conn = mysqli_connect('localhost', 'tcm159', 'sGkY4651', 'Endusers');

if (!$conn) {

die("Cannot access the database.");

}

else

{

$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 . "',

email='" . $email . "' 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>Email: $email</ul></p>";

}

else

{

echo "<p>The search found no matching ticket, so a new ticket is issued.</p>";

insertData($fname, $lname, $email);

}

Page 32: SELECT FROM Orders WHERE Amount > 200;students.cypresscollege.edu/cis246/lc12.pdfcode base as MySQL server 5.5 and aims to maintain compatibility with Oracle-owned MySQL version. Seeing

PHP – Penn Wu, PhD

354

}

mysqli_close($conn);

}

///////// function for delete ///////////

function deleteData($ticketno)

{

$conn = mysqli_connect('localhost', 'tcm159', 'sGkY4651', 'Endusers');

if (!$conn) {

die("Cannot access the database.");

}

else

{

$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>";

}

else

{

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>

Page 33: SELECT FROM Orders WHERE Amount > 200;students.cypresscollege.edu/cis246/lc12.pdfcode base as MySQL server 5.5 and aims to maintain compatibility with Oracle-owned MySQL version. Seeing

PHP – Penn Wu, PhD

355

<body>

<form action="<?php 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>

<?php

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

else {

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

}

else

{

Page 34: SELECT FROM Orders WHERE Amount > 200;students.cypresscollege.edu/cis246/lc12.pdfcode base as MySQL server 5.5 and aims to maintain compatibility with Oracle-owned MySQL version. Seeing

PHP – Penn Wu, PhD

356

echo "SQL statement executed successfully.";

}

}

else { 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', '1974-10-18');

INSERT INTO Actress Value('A1024', 'Kim', 'Zimmer', '1955-02-02');

INSERT INTO Actress Value('A1025', 'Lucy', 'Liu', '1969-12-02');

INSERT INTO Actress Value('A1026', 'Jennifer', 'Lopez', '1969-07-24');

3 UPDATE Actress SET BirthDate='1968-12-02' 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]

Page 35: SELECT FROM Orders WHERE Amount > 200;students.cypresscollege.edu/cis246/lc12.pdfcode base as MySQL server 5.5 and aims to maintain compatibility with Oracle-owned MySQL version. Seeing

PHP – Penn Wu, PhD

357

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

Page 36: SELECT FROM Orders WHERE Amount > 200;students.cypresscollege.edu/cis246/lc12.pdfcode base as MySQL server 5.5 and aims to maintain compatibility with Oracle-owned MySQL version. Seeing

PHP – Penn Wu, PhD

358

Table: Company CID CompanyName ContactPerson PhoneNumber MailingAddress City State LastContactedDate

A1012 MatLab Inc. Helen

Carnegie

4842154261 17895 Via San Pedro

St.

Long

Beach

CA 2025-11-04

A1025 MathWorks

Corp.

Betty Simens 9513375483 22157 Anderson Blvd. Pomona CA 2025-11-04

A1039 SouthDame Co. Anna Ariel 6065249744 1012 Main St. West

Hills

CA 2025-11-04

A1043 Eastern

Technology

Jenny Ngo 8180214563 4329 Kimberly Court Cypress CA 2025-11-04

A1056 Aspen

Sciences.

Erica

Strickland

2134847211 9120 Hackbart Rd. Irvine CA 2025-11-04

A1064 Harazawa

Foods.

Mariko Yamada 7146358527 17652 Central Ave. Long

Beach

CA 2025-11-04

A1078 Tong Hai

Precisions.

Linda Zhao 4157412836 22336 Wiley Dr. Diamond

Bar

CA 2025-11-04

A1081 Worcester

Institute

Stacy Barger 4506225014 11438 Glory St. Chino

Hills

CA 2025-11-04

A1097 Texas Watches Lucy Park 7013438983 396 Spectrum Parkway Irvine CA 2025-11-04

Table: Orders InvoiceNo CID OrderDate ShipDate Total UnpaiedBalance LastPaymentDate

S310221 A1012 2025-10-21 2025-10-21 6759.94 676.00 2025-11-15

S310222 A1097 2025-10-21 2025-10-22 375.52 0.00 2025-11-15 S310223 A1039 2025-10-21 2025-10-22 1239.87 124.00 2025-11-15 S310224 A1043 2025-10-21 2025-10-21 447.05 0.00 2025-11-15 S310225 A1039 2025-10-21 2025-10-21 2603.41 0.00 2025-11-15 S310226 A1064 2025-10-21 2025-10-22 257.89 0.00 2025-11-15 S310227 A1039 2025-10-21 2025-10-22 4400.00 0.00 2025-11-15 S310228 A1012 2025-10-21 2025-10-21 1782.81 0.00 2025-11-15 S310229 A1097 2025-10-21 2025-10-22 980.46 98.05 2025-11-15 S310230 A1039 2025-10-21 2025-10-22 5403.86 540.39 2025-11-15

Table: PaymentMethod CID Option1 Option2

A1012 CreditCard Net15

A1025 CreditCard Net10 A1039 CreditCard Net10 A1043 CreditCard Net7 A1056 CreditCard Net15 A1064 CreditCard Net10 A1078 CreditCard Net15 A1081 CreditCard Net10 A1097 CreditCard Net10

Database: Clients

Table: ContactPerson PID CID FirstName LastName CellPhone Email

P10121 A1012 Helen Carnegie 4842154261 [email protected]

P10251 A1025 Betty Siemens 9513375483 [email protected]

P10391 A1039 Lisa Simons 9513375497 [email protected]

P10392 A1039 Anna Ariel 6065249744 aariel@ gmail.com

P10431 A1043 Jenny Ngo 8180214563 [email protected]

P10561 A1056 Erica Strickland 2134847211 [email protected]

P10641 A1064 Mariko Yamada 7146358527 myamada@ hotmail.com

P10781 A1078 Mary Chen 4157412832 [email protected]

P10782 A1078 Linda Zhao 4157412836 [email protected]

P10811 A1081 Stacy Barger 4506225014 [email protected]

P10971 A1097 Nancy Park 7013438983 npark@ hotmail.com

P10972 A1097 Judy Park 7013438985 jpark@ hotmail.com

P10973 A1097 Lucy Park 7013438988 lpark@ hotmail.com

ContactPerson

PID (pk, fk) CID (fk)

FirstName

LastName CellPhone

Email

CreditRating

PID (pk, fk) Rating

CreditAgent

Page 37: SELECT FROM Orders WHERE Amount > 200;students.cypresscollege.edu/cis246/lc12.pdfcode base as MySQL server 5.5 and aims to maintain compatibility with Oracle-owned MySQL version. Seeing

PHP – Penn Wu, PhD

359

Table: CreditRating PID Rating CreditAgent

P10121 758 CBT1

P10251 779 ESM1

P10391 801 DYK1

P10392 798 CBT1

P10431 793 ESM1

P10561 742 CBT1

P10641 733 DYK1

P10781 775 CBT1

P10782 756 DYK1

P10811 758 CBT1

P10971 790 CBT1

P10972 787 ESM1

P10973 776 DYK1

Database: Endusers

Table: Tickets ticketNo FirstName LastName Email flag

DB16-10041 Nancy Jefferson [email protected] 0

DB16-10118 Kimberly Chen [email protected] 0

DB16-12345 Nicole Simpson [email protected] 0

DB16-20021 Jane Horita [email protected] 0

DB16-20500 George Bush [email protected] 0

DB16-24381 Sandy Liu [email protected] 0

DB16-33040 Linda Buffet [email protected] 0

DB16-46001 Bob Smith [email protected] 0

DB16-46556 Miguel Garcia [email protected] 0

DB16-58102 David Tanaka [email protected] 0

DB16-63256 Leslie Yamaguchi [email protected] 0

DB16-78210 Stephanie Crockett [email protected] 0

DB16-84214 Erica Cartman [email protected] 0

DB16-87693 Pedro Manrique [email protected] 0

DB16-98052 Bill Gates [email protected] 0

Appendix B: SQL Scripts:

DROP USER IF EXISTS tcm159@localhost;

FLUSH PRIVILEGES;

############ 1st database Customers ###############

DROP DATABASE IF EXISTS Customers;

CREATE DATABASE IF NOT EXISTS Customers;

USE Customers;

CREATE TABLE IF NOT EXISTS Company (

CID varchar(5) NOT NULL,

CompanyName varchar(40) NOT NULL,

ContactPerson varchar(35) NOT NULL,

PhoneNumber varchar(10) NOT NULL,

MailingAddress varchar(50) NOT NULL,

City varchar(25) NOT NULL,

State varchar(2) NOT NULL,

LastContactedDate Date NOT NULL, ##in 'YYYY-MM-DD' format

PRIMARY KEY(CID)

);

INSERT INTO Company VALUES ('A1012', 'MatLab Inc.', 'Helen Carnegie', '4842154261', '17895 Via

San Pedro St.', 'Long Beach', 'CA', '2025-11-04');

INSERT INTO Company VALUES ('A1025', 'MathWorks Corp.', 'Betty Simens', '9513375483', '22157

Anderson Blvd.', 'Pomona', 'CA', '2025-11-04');

INSERT INTO Company VALUES ('A1039', 'SouthDame Co.', 'Anna Ariel', '6065249744', '1012 Main

St.', 'West Hills', 'CA', '2025-11-04');

INSERT INTO Company VALUES ('A1043', 'Eastern Technology', 'Jenny Ngo', '8180214563', '4329

Kimberly Court', 'Cypress', 'CA', '2025-11-04');

INSERT INTO Company VALUES ('A1056', 'Aspen Sciences.', 'Erica Strickland', '2134847211', '9120

Hackbart Rd.', 'Irvine', 'CA', '2025-11-04');

Page 38: SELECT FROM Orders WHERE Amount > 200;students.cypresscollege.edu/cis246/lc12.pdfcode base as MySQL server 5.5 and aims to maintain compatibility with Oracle-owned MySQL version. Seeing

PHP – Penn Wu, PhD

360

INSERT INTO Company VALUES ('A1064', 'Harazawa Foods.', 'Mariko Yamada', '7146358527', '17652

Central Ave.', 'Long Beach', 'CA', '2025-11-04');

INSERT INTO Company VALUES ('A1078', 'Tong Hai Precisions.', 'Linda Zhao', '4157412836', '22336

Wiley Dr.', 'Diamond Bar', 'CA', '2025-11-04');

INSERT INTO Company VALUES ('A1081', 'Worcester Institute', 'Stacy Barger', '4506225014', '11438

Glory St.', 'Chino Hills', 'CA', '2025-11-04');

INSERT INTO Company VALUES ('A1097', 'Texas Watches', 'Lucy Park', '7013438983', '396 Spectrum

Parkway', 'Irvine', 'CA', '2025-11-04');

CREATE TABLE IF NOT EXISTS Orders (

InvoiceNo varchar(7) NOT NULL,

CID varchar(5) NOT NULL,

OrderDate Date NOT NULL, ##in 'YYYY-MM-DD' format

ShipDate Date NOT NULL, ##in 'YYYY-MM-DD' format

Total decimal(10,2),

UnpaidBalance decimal(10,2),

LastPaymentDate Date NOT NULL, ##in 'YYYY-MM-DD' format

PRIMARY KEY(InvoiceNo)

);

INSERT INTO Orders VALUES ('S310221', 'A1012', '2025-10-21', '2025-10-21', 6759.94, 676.00,

'2025-11-15');

INSERT INTO Orders VALUES ('S310222', 'A1097', '2025-10-21', '2025-10-22', 375.52, 0.00, '2025-

11-15');

INSERT INTO Orders VALUES ('S310223', 'A1039', '2025-10-21', '2025-10-22', 1239.87, 124.00,

'2025-11-15');

INSERT INTO Orders VALUES ('S310224', 'A1043', '2025-10-21', '2025-10-21', 447.05, 0.00, '2025-

11-15');

INSERT INTO Orders VALUES ('S310225', 'A1039', '2025-10-21', '2025-10-21', 2603.41, 0.00, '2025-

11-15');

INSERT INTO Orders VALUES ('S310226', 'A1064', '2025-10-21', '2025-10-22', 257.89, 0.00, '2025-

11-15');

INSERT INTO Orders VALUES ('S310227', 'A1039', '2025-10-21', '2025-10-22', 4400.00, 0.00, '2025-

11-15');

INSERT INTO Orders VALUES ('S310228', 'A1012', '2025-10-21', '2025-10-21', 1782.81, 0.00, '2025-

11-15');

INSERT INTO Orders VALUES ('S310229', 'A1097', '2025-10-21', '2025-10-22', 980.46, 98.05, '2025-

11-15');

INSERT INTO Orders VALUES ('S310230', 'A1039', '2025-10-21', '2025-10-22', 5403.86, 540.39,

'2025-11-15');

CREATE TABLE IF NOT EXISTS PaymentMethod (

CID varchar(5) NOT NULL,

Option1 varchar(20) NOT NULL,

Option2 varchar(20) NOT NULL,

PRIMARY KEY(CID)

);

INSERT INTO PaymentMethod VALUES ('A1012', 'CreditCard', 'Net15');

INSERT INTO PaymentMethod VALUES ('A1025', 'CreditCard', 'Net10');

INSERT INTO PaymentMethod VALUES ('A1039', 'CreditCard', 'Net10');

INSERT INTO PaymentMethod VALUES ('A1043', 'CreditCard', 'Net7');

INSERT INTO PaymentMethod VALUES ('A1056', 'CreditCard', 'Net15');

INSERT INTO PaymentMethod VALUES ('A1064', 'CreditCard', 'Net10');

INSERT INTO PaymentMethod VALUES ('A1078', 'CreditCard', 'Net15');

INSERT INTO PaymentMethod VALUES ('A1081', 'CreditCard', 'Net10');

INSERT INTO PaymentMethod VALUES ('A1097', 'CreditCard', 'Net10');

############ 2nd database Clients ###############

DROP DATABASE IF EXISTS Clients;

CREATE DATABASE IF NOT EXISTS Clients;

USE Clients;

CREATE TABLE IF NOT EXISTS ContactPerson (

PID varchar(6) NOT NULL,

CID varchar(5) NOT NULL,

FirstName varchar(20) NOT NULL,

LastName varchar(20) NOT NULL,

Page 39: SELECT FROM Orders WHERE Amount > 200;students.cypresscollege.edu/cis246/lc12.pdfcode base as MySQL server 5.5 and aims to maintain compatibility with Oracle-owned MySQL version. Seeing

PHP – Penn Wu, PhD

361

CellPhone varchar(10) NOT NULL,

Email varchar(30) NOT NULL,

PRIMARY KEY(PID)

);

INSERT INTO ContactPerson VALUES ('P10121', 'A1012', 'Helen ', 'Carnegie', '4842154261',

'[email protected]');

INSERT INTO ContactPerson VALUES ('P10251', 'A1025', 'Betty ', 'Siemens', '9513375483',

'[email protected]');

INSERT INTO ContactPerson VALUES ('P10391', 'A1039', 'Lisa ', 'Simons', '9513375497',

'[email protected]');

INSERT INTO ContactPerson VALUES ('P10392', 'A1039', 'Anna ', 'Ariel', '6065249744', 'aariel@

gmail.com');

INSERT INTO ContactPerson VALUES ('P10431', 'A1043', 'Jenny ', 'Ngo', '8180214563',

'[email protected]');

INSERT INTO ContactPerson VALUES ('P10561', 'A1056', 'Erica ', 'Strickland', '2134847211',

'[email protected]');

INSERT INTO ContactPerson VALUES ('P10641', 'A1064', 'Mariko ', 'Yamada', '7146358527', 'myamada@

hotmail.com');

INSERT INTO ContactPerson VALUES ('P10781', 'A1078', 'Mary', 'Chen', '4157412832',

'[email protected]');

INSERT INTO ContactPerson VALUES ('P10782', 'A1078', 'Linda ', 'Zhao', '4157412836',

'[email protected]');

INSERT INTO ContactPerson VALUES ('P10811', 'A1081', 'Stacy ', 'Barger', '4506225014',

'[email protected]');

INSERT INTO ContactPerson VALUES ('P10971', 'A1097', 'Nancy ', 'Park', '7013438983', 'npark@

hotmail.com');

INSERT INTO ContactPerson VALUES ('P10972', 'A1097', 'Judy ', 'Park', '7013438985', 'jpark@

hotmail.com');

INSERT INTO ContactPerson VALUES ('P10973', 'A1097', 'Lucy ', 'Park', '7013438988', 'lpark@

hotmail.com');

CREATE TABLE IF NOT EXISTS CreditRating (

PID varchar(6) NOT NULL,

Rating int(4) NOT NULL,

CreditAgent varchar(4) NOT NULL,

PRIMARY KEY(PID)

);

INSERT INTO CreditRating VALUES ('P10121', 758, 'CBT1');

INSERT INTO CreditRating VALUES ('P10251', 779, 'ESM1');

INSERT INTO CreditRating VALUES ('P10391', 801, 'DYK1');

INSERT INTO CreditRating VALUES ('P10392', 798, 'CBT1');

INSERT INTO CreditRating VALUES ('P10431', 793, 'ESM1');

INSERT INTO CreditRating VALUES ('P10561', 742, 'CBT1');

INSERT INTO CreditRating VALUES ('P10641', 733, 'DYK1');

INSERT INTO CreditRating VALUES ('P10781', 775, 'CBT1');

INSERT INTO CreditRating VALUES ('P10782', 756, 'DYK1');

INSERT INTO CreditRating VALUES ('P10811', 758, 'CBT1');

INSERT INTO CreditRating VALUES ('P10971', 790, 'CBT1');

INSERT INTO CreditRating VALUES ('P10972', 787, 'ESM1');

INSERT INTO CreditRating VALUES ('P10973', 776, 'DYK1');

############ 3rd database Clients ###############

DROP DATABASE IF EXISTS Endusers;

CREATE DATABASE IF NOT EXISTS Endusers;

USE Endusers;

CREATE TABLE IF NOT EXISTS tickets (

ticketNo varchar(10) NOT NULL,

FirstName varchar(25) NOT NULL,

LastName varchar(25) NOT NULL,

Email varchar(50) NOT NULL,

flag int(1) NOT NULL,

PRIMARY KEY(ticketNo)

);

INSERT INTO tickets VALUES ('DB16-24381', 'Sandy', 'Liu', '[email protected]', 0);

INSERT INTO tickets VALUES ('DB16-33040', 'Linda', 'Buffet', '[email protected]', 0);

Page 40: SELECT FROM Orders WHERE Amount > 200;students.cypresscollege.edu/cis246/lc12.pdfcode base as MySQL server 5.5 and aims to maintain compatibility with Oracle-owned MySQL version. Seeing

PHP – Penn Wu, PhD

362

INSERT INTO tickets VALUES ('DB16-20500', 'George', 'Bush', '[email protected]', 0);

INSERT INTO tickets VALUES ('DB16-84214', 'Erica', 'Cartman', '[email protected]', 0);

INSERT INTO tickets VALUES ('DB16-78210', 'Stephanie', 'Crockett', '[email protected]', 0);

INSERT INTO tickets VALUES ('DB16-20021', 'Jane', 'Horita', '[email protected]', 0);

INSERT INTO tickets VALUES ('DB16-98052', 'Bill', 'Gates', '[email protected]', 0);

INSERT INTO tickets VALUES ('DB16-10041', 'Nancy', 'Jefferson', '[email protected]', 0);

INSERT INTO tickets VALUES ('DB16-10118', 'Kimberly', 'Chen', '[email protected]', 0);

INSERT INTO tickets VALUES ('DB16-58102', 'David', 'Tanaka', '[email protected]', 0);

INSERT INTO tickets VALUES ('DB16-46556', 'Miguel', 'Garcia', '[email protected]', 0);

INSERT INTO tickets VALUES ('DB16-12345', 'Nicole', 'Simpson', '[email protected]', 0);

INSERT INTO tickets VALUES ('DB16-46001', 'Bob', 'Smith', '[email protected]', 0);

INSERT INTO tickets VALUES ('DB16-87693', 'Pedro', 'Manrique', '[email protected]', 0);

INSERT INTO tickets VALUES ('DB16-63256', 'Leslie', 'Yamaguchi', '[email protected]', 0);

####### Create Users ##########

CREATE USER 'tcm159'@'localhost' IDENTIFIED BY 'sGkY4651';

GRANT ALL PRIVILEGES ON Customers . * TO 'tcm159'@'localhost';

GRANT ALL PRIVILEGES ON Clients . * TO 'tcm159'@'localhost';

GRANT ALL PRIVILEGES ON Endusers . * TO 'tcm159'@'localhost';

FLUSH PRIVILEGES;