~~SLIDESHOW~~
Supplementary Material
Provided for Reference. This material is no longer taught on this module.
Lecturer: Dr Chris P. Jobling.
An introduction to relational databases, three-tier architecture and database driven web applications.
Based on Chapter 14 of Robert W. Sebasta, Programming the World-Wide Web, 3rd Edition, Addison Wesley, 2006. and Chapters 11 and 13 of Chris Bates, Web Programming: Building Internet Applications, 3rd Edition, John Wiley, 2006. Chris Bates, Web Programming: Building Internet Applications, 3rd Edition, John Wiley, 2006.
Introducing Databases and Database Access with PHP/MySQL
You should be able to answer the following questions:
NOT NULL
constraint specify in a column of a CREATE TABLE SQL
command? SELECT
clause? You should be able to answer the following questions:
WHERE
clause of a SELECT
command? INSERT
command? UPDATE
command: If you have any difficulty, read the additional notes on SQL.
“Reading” the diagram we have a corvette belongs to a state and there are many corvettes in a state. Corvettes have one or more pieces of equipment, equipment can belong to more than one corvette. 1 to many relationships indicate a foreign key in the many side. Many to many relationships require a relationship table.
Vette_id | Body_style | Miles | Year | State |
---|---|---|---|---|
1 | coupe | 18.0 | 1997 | 4 |
2 | hatchback | 58.0 | 1996 | 7 |
3 | convertible | 13.5 | 2001 | 1 |
4 | hatchback | 19.0 | 1995 | 2 |
5 | hatchback | 25.0 | 1991 | 5 |
6 | hardtop | 15.0 | 2000 | 2 |
7 | coupe | 55.0 | 1979 | 10 |
8 | convertible | 17.0 | 1999 | 5 |
9 | hardtop | 17.0 | 2000 | 5 |
10 | hatchback | 50.0 | 1995 | 7 |
State_id | State |
---|---|
1 | Alabama |
2 | Alaska |
3 | Arizona |
4 | Arkansas |
5 | California |
6 | Colorado |
7 | Connecticut |
8 | Delaware |
9 | Florida |
10 | Georgia |
: | : |
51 | Wyoming |
Equp_id | Equip |
---|---|
1 | Automatic |
2 | 4-speed |
3 | 5-speed |
4 | 6-speed |
5 | CD |
6 | Leather |
Vette_id | Equip |
---|---|
1 | 1 |
1 | 5 |
1 | 6 |
2 | 1 |
2 | 5 |
2 | 6 |
3 | 1 |
3 | 6 |
: | : |
10 | 5 |
CREATE TABLE
to create a database INSERT
SELECT
UPDATE
DELETE
CREATE TABLE 'states' ( 'State_id' INT(11) NOT NULL AUTO_INCREMENT, 'State' VARCHAR(25) NOT NULL, PRIMARY KEY ('State_id') ); CREATE TABLE 'corvettes' ( 'Vette_id' INT(11) NOT NULL AUTO_INCREMENT, 'Body_style' VARCHAR(25) NOT NULL, 'Miles' FLOAT NOT NULL, 'Year' YEAR(4) NOT NULL, 'State' INT(11) NOT NULL, PRIMARY KEY ('Vette_id') );
INSERT INTO Corvettes(Vette_id, Body_style, Miles, YEAR, State) VALUES (37, 'convertible', 25.5, 1986, 17)
SELECT Body_style FROM Corvettes WHERE YEAR > 1994
WHERE
clause is (often) the primary key of the row to be updated:UPDATE Corvettes SET YEAR = 1996 WHERE Vette_id = 17
DELETE FROM Corvettes WHERE Vette_id = 27
DROP TABLE IF EXISTS States
Corvettes
and Equipment
SELECT
can build a temporary table with info from two tables, from which the desired results can be gotten – this is called a join of the two tables SELECT
that does a join operation specifies two tables in its FROM
clause and also has a compound WHERE
clauseWHERE
conditionsVette_ids
from Corvettes
and Corvettes_Equipment
must matchEquip
from Corvettes_Equipment
must match the Equip_id
from Equipment
Equip
from Equipment
must be 'CD
'SELECT Corvettes.Vette_id, Corvettes.Body_style, Corvettes.Miles, Corvettes.Year, Corvettes.State, Equipment.Equip FROM Corvettes, Equipment WHERE Corvettes.Vette_id = Corvettes_Equipment.Vette_id AND Corvettes_Equipment.Equip = Equipment.Equip_id AND Equipment.Equip = 'CD'
VETTE_ID | BODY_STYLE | MILES | YEAR | STATE | EQUIP |
---|---|---|---|---|---|
1 | coupe | 18.0 | 1997 | 4 | CD |
2 | hatchback | 58.0 | 1996 | 7 | CD |
8 | convertible | 17.0 | 1999 | 5 | CD |
9 | hardtop | 17.0 | 2000 | 5 | CD |
10 | hatchback | 50.0 | 1995 | 7 | CD |
At the end of this lecture you should be able to answer these questions:
At the end of this lecture you should be able to answer these questions:
auto_increment
do? mysql_select_db
function? At the end of this lecture you should be able to answer these questions:
mysql_fetch_array
do? mysql_fetch_array
. mysql [-h host] [-u username] [database name] [-p]
<note>
host
is the name of the MySQL server – default is the user's machine username
is that of the owner of the database – default is the name used to log into the system </note>
use cars;
Database changed
ERROR 1046: No Database Selected
CREATE DATABASE cars;
Query ok, 1 row affected (0.05 sec)
* Example:
CREATE TABLE Equipment (Equip_id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, Equip CHAR(10));
SHOW TABLES;
DESCRIBE Corvettes;
htmlspecialchars($str)
?
, “
, \
, and NULL
), which could come from $_GET
and $_POST
magic_quotes_gpc
in the PHP.ini
file is set to ON
by default$query = "SELECT * FROM Names WHERE Name = $name";
$name
is O'Shanter
, it would prematurely terminate the query stringmagic_quotes_gpc
on, it will be converted to O\'Shanter
SELECT
clause has a single-quoted part, like 'California
', the single quotes will be implicitly backslashed, making the query illegal for MySQL magic_quotes_gpc
must be turned off, or else the extra backslashes can be removed with stripslashes
mysql_connect
, which can have three parameters:host
(default is localhost) username
(default is the username of the PHP script – i.e. effective user id of web server) password
(default is blank, which works if the database does not require a password) $db = mysql_connect();
mysql_close
mysql_select_db("cars");
mysql_query
with a string parameter, which is an SQL command:$query = "SELECT * from States"; $result = mysql_query($query);
$num_rows = mysql_num_rows($result);
mysql_fetch_array
:for ($row_num = 0; $row_num < $num_rows; $row_num++) { $row = mysql_fetch_array($result); print "<p> Result row number" . ($row_num + 1) . " State_id: "; print htmlspecialchars($row["State_id"]); print "State: "; : }
(1, Alabama)
, the array has:((0, 1), (State_id, 1), (1, Alabama), (State, Alabama))
$row
:$values = array_values($row); for ($index = 0; $index < $num_fields / 2; $index++) print "$values[2 * $index + 1] <br />";
$keys = array_keys($row); for ($index = 0; $index < $num_fields; $index++) print "$keys[2 * $index + 1] <br />";
$_POST
<note warning>
For reasons of security, examples are designed to work from a local installation. I used DocumentRoot/eg-259/examples/lecture19
and created the cars database using phpMyAdmin. Data for cars database etc, is available on Blackboard site.
</note>
<!DOCTYPE html> <!-- carsdata.html Uses a form to collect a query against the cars database. Calls the PHP script, access_cars.php to perform the given query and display the results --> <html lang="en"> <head> <meta charset="utf-8" /> <title> Access to the corvettes database </title> </head> <body> <p> Try: <pre> SELECT Vette_id, Body_style, Year, States.State FROM Corvettes, States WHERE Corvettes.State = States.State_id AND States.State = 'California' </pre> Please enter your query: <br /> <form action = "access_cars.php" method = "post"> <textarea rows = "2" cols = "80" name = "query" > </textarea> <br /> <br /> <input type = "reset" value = "Reset" /> <input type = "submit" value = "Submit request" /> </form> </p> </body> </html>
<!DOCTYPE html> <!-- access_cars.php A PHP script to access the cars database through MySQL --> <html lang="en"> <head> <meta charset="utf-8" /> <title> Access the cars database with MySQL </title> </head> <body> <?php // Connect to MySQL $db = mysql_connect("localhost", "eg-259", "eg-259"); if (!$db) { print "Error - Could not connect to MySQL"; exit ; } // Select the cars database $er = mysql_select_db("cars"); if (!$er) { print "Error - Could not select the cars database"; exit ; } // Get the query and clean it up (delete leading and trailing // whitespace and remove backslashes from magic_quotes_gpc) $query = $_POST['query']; trim($query); $query = stripslashes($query); // Display the query, after fixing html characters $query_html = htmlspecialchars($query); print "<p> <b> The query is: </b> " . $query_html . "</p>"; // Execute the query $result = mysql_query($query); if (!$result) { print "Error - the query could not be executed"; $error = mysql_error(); print "<p>" . $error . "</p>"; exit ; } // Display the results in a table print "<table border='1'><caption> <h2> Query Results </h2> </caption>"; print "<tr>"; // Get the number of rows in the result, as well as the first row // and the number of fields in the rows $num_rows = mysql_num_rows($result); $row = mysql_fetch_array($result); $num_fields = mysql_num_fields($result); // Produce the column labels $keys = array_keys($row); for ($index = 0; $index < $num_fields; $index++) print "<th>" . $keys[2 * $index + 1] . "</th>"; print "</tr>"; // Output the values of the fields in the rows for ($row_num = 0; $row_num < $num_rows; $row_num++) { print "<tr>"; $values = array_values($row); for ($index = 0; $index < $num_fields; $index++) { $value = htmlspecialchars($values[2 * $index + 1]); print "<td>" . $value . "</td> "; } print "</tr>"; $row = mysql_fetch_array($result); } print "</table>"; ?> </body> </html>
action
attribute of the form to the name of the combined document file <input type = "hidden" name = "stage" value = "1" />
$stage = $_POST["stage"]; if (!IsSet($stage))) { ... }
then
clause includes the form processing; else
clause includes the form display <!DOCTYPE html> <!-- access_cars2.php A PHP script to both get a query from the user and access the cars database through MySQL to get and display the result of the query. --> <html lang="en"> <head> <meta charset="utf-8" /> <title> Access the cars database with MySQL </title> </head> <body> <?php $stage = $_POST["stage"]; if (!IsSet($stage)) { ?> <p> Try: <pre> SELECT Vette_id, Body_style, Year, States.State FROM Corvettes, States WHERE Corvettes.State = States.State_id AND States.State = 'California' </pre> Please enter your query: <br /> <form method = "POST" action = "access_cars2.php" > <textarea rows = "2" cols = "80" name = "query"> </textarea> <br /> <br /> <input type = "hidden" name = "stage" value = "1" /> <input type = "submit" value = "Submit request" /> </form> </p> <?php } else { // $stage was set, so process the query // Connect to MySQL $db = mysql_connect("localhost", "eg-259", "eg-259"); if (!$db) { print "Error - Could not connect to MySQL"; exit; } // Select the cars database $er = mysql_select_db("cars"); if (!$er) { print "Error - Could not select the cars database"; exit; } // Get the query and clean it up (delete leading and trailing // whitespace and remove backslashes from magic_quotes_gpc) $query = $_POST['query']; trim($query); $query = stripslashes($query); // Fix the query for browser display and display it $query_html = htmlspecialchars($query); print "<p> <b> The query is: </b> " . $query_html . "</p>"; // Execute the query $result = mysql_query($query); if (!$result) { print "Error - the query could not be executed"; $error = mysql_error(); print "<p>" . $error . "</p>"; exit; } // Display the results in a table print "<table border='1'><caption> <h2> Query Results </h2> </caption>"; print "<tr>"; // Get the number of rows in the result, as well as the first row // and the number of fields in the rows $num_rows = mysql_num_rows($result); $row = mysql_fetch_array($result); $num_fields = mysql_num_fields($result); // Produce the column labels $keys = array_keys($row); for ($index = 0; $index < $num_fields; $index++) { print "<th>" . $keys[2 * $index + 1] . "</th>"; } print "</tr>"; // Output the values of the fields in the rows for ($row_num = 0; $row_num < $num_rows; $row_num++) { print "<tr>"; $values = array_values($row); for ($index = 0; $index < $num_fields; $index++){ $value = htmlspecialchars($values[2 * $index + 1]); print "<td>" . $value . "</td> "; } print "</tr>"; $row = mysql_fetch_array($result); } print "</table>"; } ?> </body> </html>
Introducing Databases and Database Access with PHP/MySQL
At the end of this lecture you should be able to answer these questions:
At the end of this lecture you should be able to answer these questions:
auto_increment
do? mysql_select_db
function? At the end of this lecture you should be able to answer these questions:
mysql_fetch_array
do? mysql_fetch_array
. access_cars.php
to handle UPDATE
and INSERT
SQL commands.