4 - MySQL & PHP PDF
4 - MySQL & PHP PDF
2
Introduction to Databases
A database is an ordered collection of information from which a
computer program can quickly access information
Each row in a database table is called a record (tuple)
A record in a database is a single complete set of related information
Each column in a database table is called a field (attribute)
Fields are the individual categories of information stored in a record
4
One-to-One Relationships
A one-to-one relationship exists between two tables when a
related table contains exactly one record for each record in the
primary table
Create one-to-one relationships to break information into multiple,
logical sets
Information in the tables in a one-to-one relationship can be
placed within a single table
Make the information in one of the tables confidential and
accessible only by certain individuals
Alternatively, create a base table including all information about
an object, and then create views for different people to access
5
One-to-One Relationships (continued)
One-to-one relationship
6
One-to-Many Relationship
A one-to-many relationship exists in a relational database when
one record in a primary table has many related records in a
related table
Breaking tables into multiple related tables to reduce redundant
information is called normalization
Provides a more efficient and less redundant method of storing
this information in a database
7
One-to-Many Relationship (continued)
8
One-to-Many Relationship (continued)
9
Many-to-Many Relationship
A many-to-many relationship exists in a relational database
when many records in one table are related to many records in
another table
e.g. relationship between programmers and languages
Must use a junction table which creates a one-to-many
relationship for each of the two tables in a many-to-many
relationship
A junction table contains foreign keys from the two tables
10
Many-to-Many Relationship (continued)
Many-to-many
relationship
11
Working with Database Management Systems
A relational database management system (or RDBMS) is a
system that stores and manages data in a relational format
A schema is the structure of a database including its tables,
fields, and relationships
A query is a structured set of instructions and criteria for
retrieving, adding, modifying, and deleting database information
Structured query language (or SQL – pronounced as sequel) is
a standard data manipulation language used among many
database management systems
Open database connectivity (or ODBC) allows ODBC-
compliant applications to access any data source for which there
is an ODBC driver
12
Getting Started with MySQL
MySQL is an open source database server, and it is fast and
reliable.
There are several ways to interface with a MySQL database
server:
Using MySQL Monitor, a command-line program
Using phpMyAdmin, a web interface program
( http://mercury.ict.swin.edu.au/mysql/ )
https://feenix-mariadb-web.swin.edu.au/ - in new server
Using PHP database functions within PHP scripts
See: https://csg.ict.swin.edu.au/livecsg/help/Doc_databases_student_mysql
13
Logging in to MySQL Monitor
We will be accessing the MySQL database server after you login
to mercury. Your account and database have been created.
Login to the mercury.swin.edu.au server using ‘putty’ client.
To access your MySQL (MariaDB) account, type in:
`mysql (press Enter key, then password)
14
Creating Users and Grant Privileges (root user)
Use a GRANT statement to create user accounts and assign
privileges
Privileges are the operations that a user can perform with a
database
The GRANT statement creates the user account if it does not exist
and assigns the specified privileges
GRANT privilege [(column)][, privilege [(columns)]]...
ON {table | * | *.* | database.*}
TO user [IDENTIFIED BY 'password'];
will add user zara with password zara123 for a particular database,
which is named as TUTORIALS.
16
(root) Revoking Privileges and Deleting Users
You must be logged in with the root account or have sufficient
privileges to revoke privileges from another user account
REVOKE privilege [(column)][, privilege [(columns)]]...
ON {table | * | *.* | database.*}
FROM user;
The REVOKE ALL PRIVILEGES statement removes all privileges
from a user account for a specified table or database
Before deleting a user, you must first revoke all privileges assigned
to the user account for all databases
Use the REVOKE ALL PRIVILEGES statement
View the privileges assigned to a user account with the SHOW GRANTS
FOR user statement
To delete an existing user, use the DROP USER user
statement to delete the account from the user table in the mysql
database
17
Creating and Deleting Databases
Use the CREATE DATABASE statement to create a new database:
mysql> CREATE DATABASE guitars;
Query OK, 1 row affected (0.02 sec)
19
Examples
20
Working with the MySQL Monitor
At the mysql> command prompt terminate the command with a
semicolon
mysql> SELECT * FROM inventory;
The SQL keywords entered in the MySQL Monitor are not case
sensitive
21
Understanding MySQL Identifiers
Identifiers for databases, tables, fields, indexes, and aliases
An alias is an alternate name used to refer to a table or field in
SQL statements
The case sensitivity of database and table identifiers depends on
the operating system
Not case sensitive on Windows platforms
Case sensitive on UNIX/Linux systems
22
Creating and Deleting Tables
The CREATE TABLE statement specifies the table and
column names and the data type for each column
CREATE TABLE table_name (column_name TYPE, ...);
23
Example - Creating Table
mysql> CREATE TABLE inventory (
item_number int NOT NULL AUTO_INCREMENT,
make varchar(30) NOT NULL,
model varchar(30) NOT NULL,
price double NOT NULL,
quantity int NOT NULL,
PRIMARY KEY (item_number)
);
24
Adding Records
Use the INSERT statement to add individual records to a table
INSERT INTO table_name (column1, column2, ...)
VALUES(value1, value2, ...);
25
Updating Records
To update records in a table, use the UPDATE statement
The syntax for the UPDATE statement is:
UPDATE table_name
SET column_name=value
WHERE condition;
The UPDATE keyword specifies the name of the table to update
The SET keyword specifies the value to assign to the fields in the records
that match the condition in the WHERE keyword
26
Deleting Records
Use the DELETE statement to delete records in a table
The syntax for the DELETE statement is:
DELETE FROM table_name
WHERE condition;
27
Retrieving Records
Use the SELECT statement to retrieve records from a table:
mysql> SELECT model, quantity FROM inventory;
28
Retrieving Records – Sorting
Use the ORDER BY keyword with the SELECT statement
to perform an alphanumeric sort of the results returned from a
query
mysql> SELECT make, model FROM inventory
-> ORDER BY make, model;
29
Accessing Databases from PHP
There are three main options when considering
connecting to a MySQL database server using PHP:
PHP's MySQL Extension
PHP's mysqli Extension We will use mysqli
PHP Data Objects (PDO)
http://www.php.net/manual/en/book.mysqli.php
30
Connecting to MySQL
Open a connection to a MySQL database server with the
mysqli_connect() function
The mysqli_connect() function returns a positive integer if it
connects to the database successfully or false if it does not
Assign the return value from the mysqli_connect() function to
a variable that you can use to access the database in your script
$connection = mysqli_connect("host"[, "user ",
"password", "database"])
The host argument specifies the host name where your MySQL database
server is installed e.g. feenix-mariadb.swin.edu.au
The user and password arguments specify a MySQL account name and
password e.g. s1234567 yourMySQLpassword
The database argument specifies a database e.g. s1234567_db
31
Selecting a Database
The function for selecting a database is
mysqli_select_db(connection, database)
32
Handling MySQL Errors
Reasons for not connecting to a database server include:
The database server is not running
Insufficient privileges to access the data source
Invalid username and/or password
33
Terminating Script Execution
The die() and exit() functions terminate script execution
The die() version is usually used when attempting to access a
data source
Both functions accept a single string argument
Call the die() and exit() functions as separate statements
or by appending either function to an expression with the or
operator
34
Handling MySQL Errors (continued)
$dbConnect = @mysqli_connect("localhost", "root", "paris");
if (!$dbConnect)
die("<p>The database server is not available.</p>");
echo "<p>Successfully connected to the database server.</p>";
$dbSelect = @mysqli_select_db($dbConnect, "flightlog");
if (!$dbSelect)
die("<p>The database is not available.</p>");
echo "<p>Successfully opened the database.</p>";
// additional statements that access the database
mysqli_close($dbConnect);
35
Handling MySQL Errors(continued)
MySQL error reporting functions
36
Handling MySQL Errors(continued)
$user = $_GET['username'];
$password = $_GET['password'];
$dbConnect = @mysqli_connect("localhost", $user, $password)
or die("<p>Unable to connect to the database server.</p>"
. "<p>Error code " . mysqli_connect_errno()
. ": " . mysqli_connect_error() . "</p>");
echo "<p>Successfully connected to the database server.</p>";
@mysqli_select_db($dbConnect, "flightlog")
or die("<p>The database is not available.</p>");
echo "<p>Successfully opened the database.</p>";
// additional statements that access the database
mysqli_close($dbConnect);
37
Handling MySQL Errors(continued)
38
Handling MySQL Errors(continued)
... ...
@mysqli_select_db($dbConnect, "flightplan")
or die("<p>Unable to select the database.</p>"
. "<p>Error code " . mysqli_errno($dbConnect)
. ": " . mysqli_error($dbConnect) . "</p>");
echo "<p>Successfully opened the database.</p>";
// additional statements that access the database
mysqli_close($dbConnect);
41
Accessing database with PHP
Step 1 – Open a connection:
Connect to the Database Server, and select the Database,
42
Accessing database with PHP
// ## 1. open the connection
// Connect to mysql server
$conn = @mysqli_connect('sqlserver','user_name','password')
Open
mysqli_free_result($results);
mysqli_close($conn); 43
Creating Databases
Use the CREATE DATABASE statement with the
mysqli_query() function to create a new database
44
Deleting Databases
Use the DROP DATABASE statement with the
mysqli_query() function
Make sure the database does exist by executing the
mysqli_select_db() function
$dbName = "real_estate";
...
if (@!mysqli_select_db($dbConnect, $dbName))
echo "<p>The $dbName database does not exist!</p>";
else {
$sqlString = "DROP DATABASE $dbName";
$queryResult = @mysqli_query($dbConnect, $sqlString)
or die("<p>Unable to execute the query.</p>"
. "<p>Error code " . mysqli_errno($dbConnect)
. ": " . mysqli_error($dbonnect)) . "</p>";
echo "<p>Successfully deleted the database.</p>";
}
mysqli_close($dbConnect); 45
Creating and Deleting Tables
To create a table, use the CREATE TABLE statement with the
mysqli_query() function
Execute the mysqli_select_db() function before
executing the CREATE TABLE statement or the new table
might be created in the wrong database
To delete a table, use the DROP TABLE statement
with the mysqli_query() function
To prevent code from attempting to create a table that already
exists or to delete a table that does not exist, use a
mysqli_query() function that either attempts to SELECT
records from the table, or attempts to ‘SHOW TABLES LIKE’
46
Creating and Deleting Tables (continued)
$dbName = "real_estate";
...
$sqlString = "CREATE TABLE commercial (
city VARCHAR(25), state VARCHAR(25),
sale_or_lease VARCHAR(25),
type_of_use VARCHAR(40), Price INT, size INT)";
$queryResult = @mysqli_query($dbConnect, $sqlString)
or die("<p>Unable to execute the query.</p>"
. "<p>Error code " . mysqli_errno($dbConnect)
. ": " . mysqli_error($dbConnect)) . "</p>";
echo "<p>Successfully created the table.</p>";
mysqli_close($dbConnect);
47
Adding Records
Note: Refer to previous notes on SQL
To Add records to a table:
Use the INSERT and VALUES keywords with the
mysqli_query() function
The values entered in the VALUES list must be in the same
order that defined in the table fields
Specify NULL in any fields that do not have a value
To Add multiple records to a table: Use the LOAD DATA
statement and the mysqli_query() function with a local
text file containing the records to be added.
48
Updating and Deleting Records
To Update records in a table:
Use the UPDATE, SET, and WHERE keywords with the
mysqli_query() function
The UPDATE keyword specifies the name of the table to update
The SET keyword specifies the value to assign to the fields in the
records that match the condition in the WHERE keyword
To Delete records from a table:
Use the DELETE and WHERE keywords with the
mysqli_query() function
The WHERE keyword determines which records to delete in the table
Be careful, if no WHERE keyword, all records are deleted !!
49
mysqli_affected_rows()
With queries that modify tables but do not return results (INSERT, UPDATE, and
DELETE queries), use the mysqli_affected_rows() function to
determine the number of affected rows by the query
$sqlString = "UPDATE inventory SET price=368.20
WHERE make='Fender' AND model='DG7'";
$queryResult = @mysqli_query($dbConnect, $sqlString)
or die("<p>Unable to execute the query.</p>"
. "<p>Error code " . mysqli_errno($dbConnect)
. ": " . mysqli_error($dbConnect) . "</p>");
echo "<p>Successfully updated "
. mysqli_affected_rows($dbConnect) . " record(s).</p>";
// print “Successfully updated 1 record(s)” if 1 record satisfies the condition.
50
Selecting Records
Use the SELECT and WHERE keywords with the
mysqli_query() function
mysqli_query(connection, query)
51
Selecting Records (continued)
Retrieving Records into an Indexed Array
$SQLstring = "select * from inventory";
$queryResult = @mysqli_query($DBConnect, $SQLstring)
The mysqli_fetch_row($queryResult) function returns the fields in
the current row of a result set into an indexed array and moves the result pointer to the
next row
echo "<table width='100%' border='1'>";
echo "<tr><th>Make</th><th>Model</th>
<th>Price</th><th>Quantity</th></tr>";
$row = mysqli_fetch_row($queryResult);
while ($row) {
echo "<tr><td>{$row[1]}</td>";
echo "<td>{$row[2]}</td>";
echo "<td>{$row[3]}</td>";
echo "<td>{$row[4]}</td></tr>";
$row = mysqli_fetch_row($queryResult);
}
echo "</table>";
52
Note: item_number in $row[0] is not displayed
Output of the Inventory Table
https://mercury.ict.swin.edu.au/wlai/Lec4/showInventory.php 53
Selecting Records (continued)
Retrieving Records into an Associative Array
The mysqli_fetch_assoc() function returns
the fields in the current row of a resultset into an associative
array and moves the result pointer to the next row
The difference between mysqli_fetch_assoc() and
mysqli_fetch_row() is that instead of returning the
fields into an indexed array, mysqli_fetch_assoc()
function returns the fields into an associate array and uses each
field name as the array key
54
Selecting Records (continued)
Accessing Query Result Information
The mysqli_num_rows() function returns the
number of rows in a query result
The mysqli_num_fields() function returns the
number of fields in a query result
Both functions accept a database result variable,
eg. a query result, as an argument
55
Selecting Records (continued)
$sqlString = "SELECT * FROM inventory";
$queryResult = @mysqli_query($dbConnect, $sqlString)
or die("<p>Unable to execute the query.</p>"
. "<p>Error code " . mysqli_errno($dbConnect)
. ": " . mysqli_error($dbConnect) . "</p>");
echo "<p>Successfully executed the query.</p>";
$numRows = mysqli_num_rows($queryResult);
$numFields = mysqli_num_fields($queryResult);
if ($numRows != 0 && $numFields != 0) {
echo "<p>Your query returned " , $numRows ,
" rows and “, $numFields , " fields.</p>";
} else {
echo "<p>Your query returned no results.</p>";
}
mysqli_close($dbConnect);
// print “Your query returned 6 rows and 5 fields”
56
Example – Searching Skillful People
https://mercury.ict.swin.edu.au/wlai/Lec4/searchSkill.php 57
Generating User Interface
<html>
<body>
<H3>List employees who have experience in a programming language.<br/></H3>
<?php
$DBConnect = @mysqli_connect("feenix-mariadb.swin.edu.au”, "<user>",“<pwd>",
"<user>_db")
Or die ("<p>Unable to connect to the database server.</p>". "<p>Error code ".
mysqli_connect_errno().": ". mysqli_connect_error()). "</p>";
// get language names from db
$SQLstring = "select language from Languages";
$queryResult = @mysqli_query($DBConnect, $SQLstring)
Or die ("<p>Unable to query the table.</p>"."<p>Error code ".
mysqli_errno($DBConnect). ": ".mysqli_error($DBConnect)). "</p>";
echo "<form>Please select a language: <select name='language'>";
$row = mysqli_fetch_row($queryResult);
while ($row) {
echo "<option value='".$row[0]."'>".$row[0]."</option>";
$row = mysqli_fetch_row($queryResult);
}
echo "</select><br/>Please input the minimum year required: <input type='text'
name='year'/><input type='submit' value='Search'/></form>";
58
mysqli_close($DBConnect);
Searching and Listing the Result
If (isset($_GET['language']) && isset($_GET['year'])) {
$DBConnect = @mysqli_connect("feenix-mariadb.swin.edu.au", "<user>",“<pwd>", "<user>_db")
Or die ("<p>Unable to connect to the database server.</p>". "<p>Error code ".
mysqli_connect_errno().": ". mysqli_connect_error()). "</p>";
$SQLstring = "select e.first_name,e.last_name,l.language,x.years FROM Employees e,
Experience x,Languages l where e.employee_id=x.employee_id and x.language_id =
l.language_id and l.language='".$_GET['language']."' and x.years>=".$_GET['year'];
$queryResult = @mysqli_query($DBConnect, $SQLstring)
Or die ("<p>Unable to query the $TableName table.</p>"."<p>Error code ".
mysqli_errno($DBConnect). ": ".mysqli_error($DBConnect)). "</p>";
echo "<p>List of Employees who have at least ", $_GET['year'], " years in ", $_GET['language'], ".</p>";
echo "<table width='100%' border='1'>";
echo "<th>First Name</th><th>Last Name</th><th>Language</th><th>Year</th>";
$row = mysqli_fetch_row($queryResult);
while ($row) { echo "<tr><td>{$row[0]}</td>"; echo "<td>{$row[1]}</td>"; echo "<td>{$row[2]}</td>";
echo "<td>{$row[3]}</td></tr>"; $row = mysqli_fetch_row($queryResult);
}
echo "</table>"; mysqli_close($DBConnect);
}
?>
</body>
59
</html>
Many-to-Many Relationship (continued)
Many-to-many
relationship
60
SQL query string
$SQLstring = "select e.first_name, e.last_name, l.language, x.years
FROM Employees e, Experience x,Languages l
where e.employee_id=x.employee_id and x.language_id =
l.language_id and l.language='" .$_GET['language']. "' and
x.years>=".$_GET['year'];
61
SQL query string
$SQLstring = "select e.first_name, e.last_name, l.language, x.years FROM Employees e,
Experience x,Languages l where e.employee_id=x.employee_id and x.language_id =
l.language_id and l.language='".$_GET['language']."' and x.years>=".$_GET['year'];
Or:
$SQLstring = "SELECT first_name, last_name, language, years FROM Employees, Experience,
Languages where Employees.employee_id= Experience.employee_id and Experience.language_id =
Languages.language_id and Languages.language='".$_GET['language']."' and
Experience.years>=".$_GET['year'];
Or:
$SQLstring = "SELECT first_name, last_name, language, years FROM Employees
INNER JOIN Experience on Employees.employee_id= Experience.employee_id
INNER JOIN Languages on Experience.language_id = Languages.language_id where
Languages.language='".$_GET['language ']." ' and Experience.years>=".$_GET['year'];
62